// 商品审批流程
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, Card, Col, message, Modal, Row, Space, Spin, Steps, Tooltip, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import PageTitleBox from "@/components/PageTitleBox";
import { handleGetExamineList } from "@/pages/examine/examineList/service";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import ProForm, { ProFormSelect, ProFormTextArea } from "@ant-design/pro-form";
import { handleGetApprovalCommodityList, handleGetBUSINESSAPPROVALDetail, handleGetCOMMODITYRUNNINGList } from "./service";
import './style.less'

const { Step } = Steps
const ProductApprovalProcess: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const modalFormRef = useRef<FormInstance>();
    const formRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    // 审批类型数据 
    const [searchTypeData, setSearchTypeData] = useState<any>()
    // 当前业务审批的枚举
    const [currentExamine, setCurrentExamine] = useState<any>()
    // 判断当前用户是否有发起按钮
    const [currentShowInitiate, setCurrentShowInitiate] = useState<boolean>(false)
    // 选择的当前商品行
    const [currentRow, setCurrentRow] = useState<any>()
    // 新增商品申请
    const [showApplyFor, setShowApplyFor] = useState<boolean>(false);
    // 商品列表数据
    const [shopData, setShopData] = useState<any>()
    // 选中的行数据
    const [selectRowList, setSelectRowList] = useState<any>()
    // 选中的行
    const [selectedOrderRowKeys, setSelectedOrderRowKeys] = useState<any>()
    // 显示类型
    const [showDetailType, setShowDetailType] = useState<any>()
    // 审批记录详情
    const [BUSINESSAPPROVALDETAIL, setBUSINESSAPPROVALDETAIL] = useState<any>()
    // 还有几个环节 拼在流程进度后面
    const [nextStepsList, setNextStepsList] = useState<any>()

    useEffect(async () => {
        await handleChangeType("6-100100")
    }, [])
    let statusList: string[] = ["0", "1000", "2000", "2010,2020,2030,2040,2050,2060,2070,2080,2090", "9000"]

    const columns: any = [
        {
            dataIndex: 'searchType',
            title: '审批类型',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInTable: true,
            valueEnum: {
                "0": "全部",
                "6-100100": "新增商品流程",
                "6-100200": "商品调价流程",
                "6-100210": "信息修改流程"
            },
            initialValue: "0",
        },
        {
            dataIndex: 'BusinessProcess_StateSearch',
            title: '流程状态',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInTable: true,
            valueEnum: {
                0: "全部",
                1: "待申请",
                2: "待审核",
                3: "审核中",
                4: "已审结"
            },
            initialValue: "0"
        },
        {
            dataIndex: 'BusinessProcess_Name',
            title: '业务名称',
            width: 300,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return <a onClick={() => {
                    setCurrentRow(record)
                    setShowApplyFor(true)
                }}>{record?.BusinessProcess_Name}</a>
            }
        },
        {
            dataIndex: 'Serverpart_Name',
            title: '服务区名称',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'ServerpartShop_Name',
            title: '门店名称',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'ApproveStaff_Name',
            title: '待审核人',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'BusinessProcess_StateText',
            title: '待审核环节',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return <a style={{
                    color: record?.BusinessProcess_StateText === '待审核' ? '#1890ff' :
                        record?.BusinessProcess_StateText === '审核中' ? 'rgb(250, 173, 20)' :
                            record?.BusinessProcess_StateText === '已审结' ? 'red' : ""
                }} onClick={() => {
                    console.log('recordrecordrecord', record);
                    setShowDetailType('detail')
                    setCurrentRow(record)
                    setShowApplyFor(true)
                }}>{record?.BusinessProcess_StateText || "-"}</a>
            }
        },
        {
            dataIndex: 'Accept_Code',
            title: '业务类别',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            valueType: "select",
            valueEnum: {
                "6-100100": "新增商品审批",
                "6-100200": "商品调价审批",
                "6-100210": "商品信息修改审批"
            },
        },
        {
            dataIndex: 'BusinessProcess_EndDate',
            title: '办结时间',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'BusinessProcess_StartDate',
            title: '流程开始',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
    ]

    const modalColumns: any = [
        {
            title: "序号",
            width: 70,
            dataIndex: "index",
            valueType: "index",
            align: 'center',
            ellipsis: true,
        },
        {
            title: "名称",
            width: 300,
            dataIndex: "COMMODITY_NAME",
            ellipsis: true,
            align: 'center',
        },
        {
            title: "条码",
            width: 150,
            dataIndex: "COMMODITY_BARCODE",
            ellipsis: true,
            align: 'center',
        },
        {
            title: "零售价",
            width: 150,
            dataIndex: "COMMODITY_RETAILPRICE",
            ellipsis: true,
            align: 'center',
        },
        {
            title: "规格",
            width: 150,
            dataIndex: "COMMODITY_RULE",
            ellipsis: true,
            align: 'center',
        },
        {
            title: "单位",
            width: 150,
            dataIndex: "COMMODITY_UNIT",
            ellipsis: true,
            align: 'center',
        },
    ]

    // 修改审批类型
    const handleChangeType = async (type: string) => {
        // 查出当前类型里面的流程数据
        const reqState: any = {
            SearchParameter: {
                APPROVALROUTE_STATES: "",
                APPROVALROUTE_VALID: 1,
                OPERATION_TYPES: type
            },
            PageIndex: 1,
            PageSize: 999999
        }
        const dataState = await handleGetAPPROVALROUTEList(reqState)
        console.log('fdsjkafjslk', dataState);
        setSearchTypeData(dataState)

        // 业务状态的枚举
        let statusObj: any = {}
        if (dataState && dataState.length > 0) {
            dataState.forEach((item: any) => {
                statusObj[item.APPROVALROUTE_STATE] = item.APPROVALROUTE_NAME
            })
        }
        setCurrentExamine(statusObj)
    }

    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <div style={{
                    width: "100%",
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 410px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        request={async (params) => {

                            const req: any = {
                                QueryType: 0,
                                SearchParameter: {
                                    Operation_Type: 6,
                                    Accept_Code: params?.searchType === "0" ? '' : params?.searchType,
                                    BusinessProcess_StateSearch: statusList[params?.BusinessProcess_StateSearch] === "0" ? '' : statusList[params?.BusinessProcess_StateSearch]
                                },
                                PageIndex: 1,
                                PageSize: 999999
                            }
                            const data = await handleGetExamineList(req)
                            console.log('data', data)
                            if (data.data && data.data.length > 0) {
                                data.data.forEach((item: any) => {
                                    if (item.BusinessProcess_State === 1000) {
                                        item.BusinessProcess_StateText = "待发起"
                                    } else if (item.BusinessProcess_State === 2000) {
                                        item.BusinessProcess_StateText = "待审核"
                                    } else if (item.BusinessProcess_State > 2000 && item.BusinessProcess_State < 9000) {
                                        item.BusinessProcess_StateText = "审核中"
                                    } else if (item.BusinessProcess_State = 9000) {
                                        item.BusinessProcess_StateText = "已审结"
                                    }
                                })


                                return { data: data.data, success: true, total: data.data.length }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                            ]
                        }}
                    />
                </div>
            </div>


            <Modal
                className="addProductModal"
                width={"70%"}
                title={currentRow?.BusinessApproval_ID ? "商品信息修改详情" : "新增商品信息修改申请"}
                open={showApplyFor}
                destroyOnClose
                onCancel={() => {
                    setShowApplyFor(false)
                    setCurrentRow(undefined)
                    setShopData([])
                    setSelectRowList([])
                    setSelectedOrderRowKeys([])
                    setShowDetailType(null)
                }}
                footer={false}
            >
                <ProForm
                    // layout={'horizontal'}
                    formRef={modalFormRef}
                    submitter={false}
                    preserve={false}
                    request={async () => {
                        if (currentRow?.BusinessApproval_ID) {
                            const req: any = {
                                BUSINESSAPPROVALId: currentRow?.BusinessApproval_ID,
                            }
                            const data = await handleGetBUSINESSAPPROVALDetail(req)
                            console.log('datadatadata', data);
                            setBUSINESSAPPROVALDETAIL(data.Result_Data)
                            let shopData: any = []
                            if (currentRow?.BusinessProcess_State === 9000) {
                                shopData = await handleGetApprovalCommodityList({
                                    ProvinceCode: currentUser?.ProvinceCode,
                                    // CommodityId: currentUser?.ProvinceCode,
                                    BusinessApprovalId: currentRow?.BusinessApproval_ID,
                                    PageIndex: 1,
                                    PageSize: 999999,
                                })
                            } else {
                                shopData = await handleGetCOMMODITYRUNNINGList({
                                    SearchParameter: {
                                        BUSINESSAPPROVAL_ID: currentRow?.BusinessApproval_ID,
                                    },
                                    PageIndex: 1,
                                    pageSize: 999999,
                                })
                            }
                            setShopData(shopData.Result_Data.List)
                            return {
                                reasonForApplication: data.Result_Data.BUSINESSAPPROVAL_DESC,
                                ServerpartId: data.Result_Data.SERVERPART_ID,
                                NextApproveStaffId: data.Result_Data.APPOVED_IDS
                            }
                        } else {
                            return {}
                        }
                    }}

                >
                    <Row gutter={8}>
                        <Col span={24}>
                            <ProFormTextArea
                                label="申请原因"
                                name="reasonForApplication"
                                rules={[{
                                    required: true,
                                    message: "请输入申请原因！"
                                }]}
                                disabled={currentRow?.BusinessProcess_State > 1000 || (currentRow?.BusinessApproval_ID && currentRow?.ApproveStaff_ID !== currentUser?.ID)}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label="服务区"
                                name="ServerpartId"
                                rules={[{
                                    required: true,
                                    message: "请选择服务区！"
                                }]}
                                request={async () => {
                                    const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)
                                    const list: any = []
                                    if (data && data.length > 0) {
                                        data.forEach((item: any) => {
                                            if (item.children && item.children.length > 0) {
                                                item.children.forEach((subItem: any) => {
                                                    list.push({ label: subItem.label, value: subItem.value })
                                                })
                                            }
                                        })
                                        data.forEach((item: any) => {
                                            list.push({ label: item.label, value: item.value })
                                        })
                                    }
                                    return list
                                }}
                                disabled={currentRow?.BusinessProcess_State > 1000 || (currentRow?.BusinessApproval_ID && currentRow?.ApproveStaff_ID !== currentUser?.ID)}
                            />
                        </Col>
                        <Col span={12} style={{ display: currentRow?.BusinessProcess_State > 1000 ? "none" : "" }}>
                            <ProFormSelect
                                label="下一环节审批人"
                                name="NextApproveStaffId"
                                rules={[{
                                    required: true,
                                    message: "请选择下一环节审批人！"
                                }]}
                                request={async () => {
                                    const reqState: any = {
                                        SearchParameter: {
                                            PROVINCE_CODE: currentUser?.ProvinceCode,
                                            APPROVALROUTE_STATES: "",
                                            APPROVALROUTE_VALID: 1,
                                            OPERATION_TYPES: "100210",

                                        },
                                        PageIndex: 1,
                                        PageSize: 999999
                                    }
                                    const dataState = await handleGetAPPROVALROUTEList(reqState)
                                    if (dataState && dataState.length > 0) {
                                        let obj: any = {}
                                        // 下面的环节
                                        let nextList: any = []
                                        console.log('dataState', dataState);

                                        dataState.forEach((item: any) => {
                                            if (item.APPROVALROUTE_STATE === 2000) {
                                                obj = item
                                            }
                                            if (item.APPROVALROUTE_STATE >= currentRow?.BusinessProcess_State) {
                                                if (item.APPROVALROUTE_STATE === currentRow?.BusinessProcess_State) {
                                                    item.status = "process"
                                                }
                                                nextList.push(item)
                                            }
                                        })

                                        setNextStepsList(nextList)

                                        let personTotal: number = obj.APPROVALSTAFF_ID.split(',').length || 0
                                        if (personTotal > 0) {
                                            let STAFFIDList: number[] = obj.APPROVALSTAFF_ID.split(',')
                                            let STAFFNAMEList: string[] = obj.APPROVALSTAFF_NAME.split(',')
                                            let list: any = []
                                            for (let i = 0; i < personTotal; i++) {
                                                list.push({ label: STAFFNAMEList[i], value: STAFFIDList[i] })
                                            }
                                            return list
                                        }
                                    }
                                }}
                                disabled={currentRow?.BusinessProcess_State > 1000 || (currentRow?.BusinessApproval_ID && currentRow?.ApproveStaff_ID !== currentUser?.ID)}
                            />
                        </Col>
                    </Row>

                </ProForm>

                <ProTable
                    search={false}
                    options={false}
                    pagination={false}
                    columns={modalColumns}
                    dataSource={shopData}
                    bordered
                    toolbar={{
                        actions: [
                            currentRow?.BusinessProcess_State > 1000 || (currentRow?.BusinessApproval_ID && currentRow?.ApproveStaff_ID !== currentUser?.ID) ? '' : <Button type={"primary"} onClick={() => {
                                // 判断服务区是否已选择
                                const values = modalFormRef.current?.getFieldsValue();
                                if (!values?.ServerpartId) {
                                    message.error("请先选择服务区！");
                                    return;
                                }
                                setShowAddShopModal(true);
                            }}>
                                选择商品
                            </Button>
                        ]
                    }}
                />

                {
                    currentRow?.BusinessProcess_State > 1000 ?
                        <Card title="流程进度" bordered className="ProcessProgress">
                            <div style={{ width: '100%' }} className="ProcessProgressBox">
                                <Steps
                                    size="small"
                                    className="multi-line-steps"
                                    direction="horizontal"
                                    progressDot={false}
                                    current={BUSINESSAPPROVALDETAIL?.approveList && BUSINESSAPPROVALDETAIL?.approveList.length ? BUSINESSAPPROVALDETAIL?.approveList.length : 0}
                                >
                                    {
                                        BUSINESSAPPROVALDETAIL?.approveList && BUSINESSAPPROVALDETAIL?.approveList.length > 0 ?
                                            BUSINESSAPPROVALDETAIL?.approveList.map((item: any, index: number) => (
                                                <Step
                                                    key={index}
                                                    style={{ minWidth: 180, maxWidth: 220 }}
                                                    status={"finish"}
                                                    title={item.APPROVED_NAME}
                                                    description={
                                                        <div>
                                                            <Tooltip title={`${item.STAFF_NAME || ''}${item.APPLYAPPROVE_INFO ? `：${item.APPLYAPPROVE_INFO}` : ''}`}>
                                                                <p>{`${item.APPLYAPPROVE_DATE || ''}`}</p>
                                                            </Tooltip>
                                                        </div>}
                                                />
                                            )) : ''
                                    }

                                    {
                                        nextStepsList && nextStepsList.length > 0 ?
                                            nextStepsList.map((item: any, index: number) => (
                                                <Step
                                                    key={index}
                                                    style={{ minWidth: 180, maxWidth: 220 }}
                                                    status={item.status === 'process' ? 'process' : 'wait'}
                                                    title={item.APPROVALROUTE_NAME}
                                                />
                                            )) : ''
                                    }
                                </Steps>
                            </div>
                        </Card>
                        : ''
                }
            </Modal>
        </div >
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(ProductApprovalProcess);
