// 新增商品审批
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, useRef, useState } from "react";
import type { FormInstance } from "antd";
import { Button, Card, Col, message, Modal, Popconfirm, Row, Space, Spin, Steps, Tooltip, Tree } from "antd";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import PageTitleBox from "@/components/PageTitleBox";
import { handleGetExamineList } from "@/pages/examine/examineList/service";
import ProForm, { ProFormDateTimePicker, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect } from "@ant-design/pro-form";
import { getServerpartTree } from "@/services/options";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import { handleGetNestingCOMMODITYTYPETree, handleGetServerpartShopTrade } from "../commodityInfo/service";
import { handleGetUSERDEFINEDTYPEList } from "../userDefinedType/service";
import useRequest from "@ahooksjs/use-request";
import moment from 'moment'
import { handleCreateCommodityProInst, handleDeleteCOMMODITY_RUNNING, handleDeleteCommodityProInst, handleGetApprovalCommodityList, handleGetBUSINESSAPPROVALDetail, handleGetCOMMODITYRUNNINGList, handleReapplyCommodityProInst, handleRejectCommodityProInst } from "../ProductApprovalProcess/service";
import './style.less'
import session from "@/utils/session";
import NewApplicationModal from "./components/newApplicationModal";
import AddShopModal from "./components/addShopModal";


const { Step } = Steps
const ProductChangeInfoApproval: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalFormRef = useRef<FormInstance>();
    const modalShopFormRef = useRef<FormInstance>();

    // 新增商品申请
    const [showApplyFor, setShowApplyFor] = useState<boolean>(false);
    // 显示新增商品的悬浮框
    const [showAddShopModal, setShowAddShopModal] = useState<boolean>(false);
    // 选择记录行的数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 选择商品行的数据
    const [currentShopRow, setCurrentShopRow] = useState<any>()
    // 商品列表数据
    const [shopData, setShopData] = useState<any>()
    const [selectSERVERPARTID, setSelectSERVERPARTID] = useState<any>()
    // 商品业态的搜索框内容
    const [commodityList, setCommodityList] = useState<any>([])
    const [selectBUSINESSTYPE, setSelectBUSINESSTYPE] = useState<any>()
    const [customClassList, setCustomClassList] = useState<any>()
    const [treeView, setTreeView] = useState<any>()
    // 审批的悬浮框
    const [approveModal, setApproveModal] = useState<boolean>(false);
    // 点击审批的行数据
    const [approveCurrentRow, setApproveCurrentRow] = useState<any>()
    // 下一个审批流程
    const [nextApproval, setNextApproval] = useState<any>()
    // 下一审批流程的审批人
    const [nextApprovalPerson, setNextApprovalPerson] = useState<any>()
    // 新增申请的加载效果
    const [addApprovalLoading, setAddApprovalLoading] = useState<boolean>(false);
    // 审批还是驳回 1 审批  2 驳回
    const [ApprovalType, setApprovaType] = useState<number>(0)
    // 审批记录详情
    const [BUSINESSAPPROVALDETAIL, setBUSINESSAPPROVALDETAIL] = useState<any>()
    // 还有几个环节 拼在流程进度后面
    const [nextStepsList, setNextStepsList] = useState<any>()
    // 判断有无发起申请的权限
    const [InitiateApplication, setInitiateApplication] = useState<boolean>(false)
    // 显示类型
    const [showDetailType, setShowDetailType] = useState<any>()
    // 加载服务区树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const req = {
            PROVINCE_CODE: currentUser?.ProvinceCode,
            COMMODITYTYPE_VALID: 1,
            ShowCode: true
        }
        const data = await handleGetNestingCOMMODITYTYPETree(req)
        setTreeView(data)
        return data
    })

    let statusList: string[] = ["0", "1000", "2000", "2010,2020,2030,2040,2050,2060,2070,2080,2090", "9000"]
    const columns: any = [
        {
            dataIndex: 'BusinessProcess_StateSearch',
            title: '流程状态',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInTable: true,
            // valueEnum: {
            //     "0": "全部",
            //     "2000": "待审核",
            //     "2010,2020,2030,2040,2050,2060,2070,2080,2090": "审核中",
            //     "9000": "已审结"
            // },
            valueEnum: {
                0: "全部",
                1: "待申请",
                2: "待审核",
                3: "审核中",
                4: "已审结"
            },
            initialValue: "0"
        },
        {
            dataIndex: 'BusinessProcess_Name',
            title: '业务名称',
            width: 300,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            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);
                    setApprovaType(1)
                    setShowDetailType('detail')
                    setCurrentRow(record)
                    setShowApplyFor(true)
                }}>{record?.BusinessProcess_StateText || "-"}</a>
            }
        },
        // {
        //     dataIndex: 'Accept_Code',
        //     title: '业务类别',
        //     width: 200,
        //     ellipsis: true,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        {
            dataIndex: 'BusinessProcess_EndDate',
            title: '办结时间',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'BusinessProcess_StartDate',
            title: '流程开始',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'option',
            title: '操作',
            valueType: 'option',
            align: 'center',
            hideInSearch: true,
            width: 180,
            fixed: "right",
            ellipsis: true,
            render: (_, record) => {
                return (
                    record?.ApproveStaff_ID === currentUser?.ID && record?.BusinessProcess_State !== 9000
                        ?
                        <Space>
                            {
                                record?.BusinessProcess_State === 1000
                                    ?
                                    <>
                                        <a onClick={() => {
                                            console.log('recordrecordrecord', record);

                                            setCurrentRow(record)
                                            setShowApplyFor(true)
                                        }}
                                        >
                                            编辑
                                        </a>
                                        <Popconfirm
                                            title="确认删除该商品审批流程吗?"
                                            onConfirm={async () => {
                                                const req: any = {
                                                    businessApprovalId: record?.BusinessApproval_ID,
                                                    UserId: currentUser?.ID
                                                }
                                                const data = await handleDeleteCommodityProInst(req)
                                                if (data.Result_Code === 100) {
                                                    message.success(data.Result_Desc)
                                                    actionRef.current?.reload()
                                                } else {
                                                    message.error(data.Result_Desc)
                                                }
                                            }}
                                        >
                                            <a>删除</a>
                                        </Popconfirm>
                                    </>
                                    : ""
                            }
                            {
                                record?.BusinessProcess_State > 1000 ?
                                    <>
                                        <a onClick={() => {
                                            setApprovaType(1)
                                            setCurrentRow(record)
                                            // setApproveCurrentRow(record)
                                            // setApproveModal(true)
                                            setShowApplyFor(true)
                                        }}
                                        >
                                            审批
                                        </a>
                                        <a onClick={() => {
                                            setApprovaType(2)
                                            setCurrentRow(record)
                                            // setApproveCurrentRow(record)
                                            // setApproveModal(true)
                                            setShowApplyFor(true)
                                        }}>
                                            驳回
                                        </a>
                                    </> : ""
                            }
                        </Space> : ""

                );
            },
        },
    ]

    useEffect(async () => {
        const req: any = {
            SearchParameter: {
                PROVINCE_CODE: currentUser?.ProvinceCode,
                APPROVALROUTE_STATES: "",
                APPROVALROUTE_VALID: 1,
                OPERATION_TYPES: "100100",
            }
        }
        const data = await handleGetAPPROVALROUTEList(req)
        console.log('datadatadatadata', data);
        // 拿到发起申请的人
        let firstSetp: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                if (item.APPROVALROUTE_STATE === 1000) {
                    firstSetp = item
                }
            })
        }
        // 判断当前用户 是否有新增权限
        let have: boolean = false
        let idList: any = firstSetp && firstSetp.APPROVALSTAFF_ID ? firstSetp.APPROVALSTAFF_ID.split(',') : ""
        console.log('idList', idList);

        if (idList.indexOf(currentUser?.ID.toString()) !== -1) {
            have = true
        }
        setInitiateApplication(have)

    }, [])

    // 新增申请的悬浮框取消的调用
    const handleNewApplicationModalCencel = () => {
        setShowApplyFor(false)
        setCurrentRow(undefined)
        setShopData([])
        setBUSINESSAPPROVALDETAIL(undefined)
        setShowDetailType(null)

        setApprovaType(0)
    }

    // 组件里面 改变shpoData的方法
    const handleChangeShopData = (list: any) => {
        setShopData(list)
    }

    // 关闭新增商品悬浮框的方法
    const handleCloseShopModal = () => {
        setShowAddShopModal(false)
        setCommodityList([])
        setCustomClassList([])
        setCurrentShopRow(undefined)
    }

    return (
        <div>
            <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: "6-100100",
                                    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: [
                                InitiateApplication ?
                                    <Button type={"primary"} onClick={() => {
                                        setShowApplyFor(true)
                                    }}>
                                        新增商品申请
                                    </Button> : ""
                            ]
                        }}
                    />
                </div>
            </div>
            {/* 新增申请的悬浮框 */}
            <NewApplicationModal modalType={1} parentRow={currentRow} tableRef={actionRef} onShow={showApplyFor} handleCencel={handleNewApplicationModalCencel} currentUser={currentUser} showDetailType={showDetailType}
                InitiateApplication={InitiateApplication} shopData={shopData} handleChangeShopData={handleChangeShopData} ApprovalType={ApprovalType} setCurrentShopRow={setCurrentShopRow} setShowAddShopModal={setShowAddShopModal} />


            {/* 新增商品的悬浮框 */}
            <AddShopModal parentRow={currentRow} onShow={showAddShopModal} currentShopRow={currentShopRow} shopData={shopData} handleCloseShopModal={handleCloseShopModal} handleChangeShopData={handleChangeShopData} currentUser={currentUser}
                treeView={treeView} />
        </div >
    )
}

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