// 商品信息修改审批
// 新增商品审批
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 { getFieldEnum, getFieldEnumTree, getServerpartTree } from "@/services/options";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import { handleGetCommodityList, handleGetNestingCOMMODITYTYPETree, handleGetServerpartShopTrade } from "../commodityInfo/service";
import { handleGetUSERDEFINEDTYPEList } from "../userDefinedType/service";
import useRequest from "@ahooksjs/use-request";
import moment from 'moment'
import { handleApproveCommodityProInst, handleCreateCommodityProInst, handleDeleteCOMMODITY_RUNNING, handleDeleteCommodityProInst, handleGetApprovalCommodityList, handleGetBUSINESSAPPROVALDetail, handleGetCOMMODITYRUNNINGList, handleReapplyCommodityProInst, handleRejectCommodityProInst } from "../ProductApprovalProcess/service";
import session from "@/utils/session";
import './style.less'
import NewApplicationModal from "../NewProductApproval/components/newApplicationModal";
import SelectShopModal from "../ProductChangePriceApproval/components/selectShopModal";
import EditShopModal from "../ProductChangePriceApproval/components/editShopModal";

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

    const ServerpartIdsList = session.get('ServerpartIdsList')
    // 新增商品申请
    const [showApplyFor, setShowApplyFor] = useState<boolean>(false);
    // 显示新增商品的悬浮框
    const [showAddShopModal, setShowAddShopModal] = useState<boolean>(false);
    // 选择的当前商品行
    const [currentRow, setCurrentRow] = 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 [selectRowList, setSelectRowList] = useState<any>()
    // 选中的行
    const [selectedOrderRowKeys, setSelectedOrderRowKeys] = useState<any>()
    // 编辑选中的商品的modal
    const [editShopModal, setEditShopModal] = useState<boolean>(false);
    // 选中需要编辑的行
    const [editSelectRow, setEditSelectRow] = useState<any>()
    // 新增申请的加载效果
    const [handleAddLoading, setHandleAddLoading] = useState<boolean>(false);
    // 审批记录详情
    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
    })

    const { loading: CommodityLoading, data: CommodityData } = useRequest(async () => {
        const data = await getFieldEnumTree({ FieldExplainField: 'CommodityTypeIds' })
        const obj: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                obj[item.value] = item.label
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        obj[subItem.value] = subItem.label
                        if (subItem.children && subItem.children.length > 0) {
                            subItem.children.forEach((thirdItem: any) => {
                                obj[thirdItem.value] = thirdItem.label
                            })
                        }
                    })
                }
            })
        }
        return obj
    })

    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={() => {
                                            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)
                                            // setApproveCurrentRow(record)
                                            // setApproveModal(true)
                                            setCurrentRow(record)
                                            setShowApplyFor(true)
                                        }}
                                        >
                                            审批
                                        </a>
                                        <a onClick={() => {
                                            setApprovaType(2)
                                            // setApproveCurrentRow(record)
                                            // setApproveModal(true)
                                            setCurrentRow(record)
                                            setShowApplyFor(true)
                                        }}>
                                            驳回
                                        </a>
                                    </> : ""
                            }

                        </Space> : ""

                );
            },
        },
    ]

    const modalColumns: any = [
        {
            title: "序号",
            width: 70,
            dataIndex: "index",
            valueType: "index",
            align: 'center',
            ellipsis: true,
        },
        {
            title: "名称",
            width: 300,
            dataIndex: "COMMODITY_NAME",
            ellipsis: true,
            align: 'center',
            render: (_, record) => {
                return record?.COMMODITY_NAME ? <a onClick={() => {
                    let obj: any = {}
                    if (shopData && shopData.length > 0) {
                        obj = shopData.filter((item: any) => item.COMMODITY_ID === record?.COMMODITY_ID)[0]
                    }
                    setEditSelectRow(obj)
                    setEditShopModal(true)
                }}>
                    {record?.COMMODITY_NAME}
                </a> : "-"
            }
        },
        {
            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',
        },
        {
            dataIndex: 'option',
            title: '操作',
            valueType: 'option',
            align: 'center',
            hideInSearch: true,
            width: 120,
            fixed: "right",
            ellipsis: true,
            render: (_, record) => {
                return (
                    <Space>
                        {
                            currentRow?.BusinessProcess_State > 1000 || (currentRow?.BusinessApproval_ID && currentRow?.ApproveStaff_ID !== currentUser?.ID) ? '' :
                                <>
                                    <a
                                        onClick={() => {
                                            let obj: any = {}
                                            if (shopData && shopData.length > 0) {
                                                obj = shopData.filter((item: any) => item.COMMODITY_ID === record?.COMMODITY_ID)[0]
                                            }
                                            setEditSelectRow(obj)
                                            setEditShopModal(true)
                                        }}
                                    >
                                        编辑
                                    </a>
                                    <Popconfirm
                                        title="确认删除该商品管理列表信息吗?"
                                        onConfirm={async () => {
                                            if (currentRow?.BusinessApproval_ID) {
                                                // 申请回到发起时候的真删
                                                const req: any = {
                                                    COMMODITY_RUNNINGId: record?.COMMODITY_ID
                                                }
                                                const data = await handleDeleteCOMMODITY_RUNNING(req)
                                                console.log('datadatadatadata', data);
                                                actionRef.current?.reload()
                                                // 实现直接删除的效果
                                                let oldData: any = JSON.parse(JSON.stringify(shopData))
                                                let list: any = []
                                                oldData.forEach((item: any) => {
                                                    if (item.COMMODITY_ID !== record?.COMMODITY_ID) {
                                                        list.push(item)
                                                    }
                                                })
                                                setShopData(list)
                                            } else {
                                                // 还未发起申请的假删
                                                console.log('record', record);
                                                let oldData: any = JSON.parse(JSON.stringify(shopData))
                                                let list: any = []
                                                oldData.forEach((item: any) => {
                                                    if (item.ADDTIME !== record?.ADDTIME) {
                                                        list.push(item)
                                                    }
                                                })
                                                setShopData(list)
                                            }
                                        }}
                                    >
                                        <a>删除</a>
                                    </Popconfirm>
                                </>
                        }

                        {
                            currentRow?.BusinessProcess_State === 9000 ?
                                <a onClick={() => {
                                    // setCurrentShopRow(record)
                                    // setShowAddShopModal(true)
                                    setEditSelectRow(record)
                                    setEditShopModal(true)
                                }}>详情</a>
                                : ''
                        }
                    </Space>
                );
            },
        },
    ]

    // 选择商品的表格结构
    const selectShopColumns: any = [
        {
            title: "商品查询",
            dataIndex: "searchText",
            hideInTable: true,
            fieldProp: {
                fieldholder: "请输入商品名称"
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>序号</div>,
            width: 70,
            dataIndex: 'index',
            hideInSearch: true,
            valueType: 'index'
        },
        {
            title: <div style={{ textAlign: 'center' }}>服务区</div>,
            width: 150,
            ellipsis: true,
            align: 'center',
            dataIndex: 'SERVERPART_ID',
            hideInSearch: true,
            valueType: "select",
            valueEnum: ServerpartIdsList,
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品业态</div>,
            width: 120,
            ellipsis: true,
            dataIndex: 'BUSINESSTYPE',
            align: 'center',
            valueType: 'select',
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'SHOPTRADE', notformate: true })

            },
            fieldProps: {
                showSearch: true,
                filterOption: (input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品类型</div>,
            width: 120,
            ellipsis: true,
            dataIndex: 'COMMODITY_TYPE',
            align: 'center',
            hideInSearch: true,
            valueEnum: CommodityData
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品名称</div>,
            width: 200,
            ellipsis: true,
            align: 'left',
            dataIndex: 'COMMODITY_NAME',
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品条码</div>,
            width: 150,
            ellipsis: true,
            align: 'left',
            dataIndex: 'COMMODITY_BARCODE',
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>零售价</div>,
            width: 70,
            ellipsis: true,
            align: 'right',
            dataIndex: 'COMMODITY_RETAILPRICE',
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>进货价</div>,
            width: 70,
            ellipsis: true,
            align: 'right',
            dataIndex: 'COMMODITY_PURCHASEPRICE',
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品单位</div>,
            width: 80,
            ellipsis: true,
            align: 'right',
            dataIndex: 'COMMODITY_UNIT',
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>状态</div>,
            width: 100,
            ellipsis: true,
            dataIndex: 'COMMODITY_STATE',
            align: 'center',
            valueType: 'select',
            valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
            initialValue: '1',
        },
        {
            title: <div style={{ textAlign: 'center' }}>审核时间</div>,
            width: 150,
            align: 'center',
            ellipsis: true,
            dataIndex: 'OPERATE_DATE',
            hideInSearch: true,
        }
    ]

    // 拿到对应的商品业态
    const handleGetCommodity = async (id: any) => {
        const req: any = {
            ProvinceCode: currentUser?.ProvinceCode,
            ServerpartId: id
        }
        const data = await handleGetServerpartShopTrade(req)
        console.log('data', data)
        setCommodityList(data)
    }

    // 请求自定义类的选择列表
    const handleGetCustomClassList = async (id: any) => {
        const req: any = {
            SearchParameter: {
                USERDEFINEDTYPE_STATE: 1,
                SERVERPART_ID: id,
                BUSINESSTYPE: selectBUSINESSTYPE
            },
            PageIndex: 1,
            PageSize: 999999,
            pageSize: 999999,
        }
        const data = await handleGetUSERDEFINEDTYPEList(req)
        if (data && data.length > 0) {
            const list: any = []
            data.forEach((item: any) => {
                list.push({ label: item.USERDEFINEDTYPE_NAME, value: item.USERDEFINEDTYPE_ID })
            })
            setCustomClassList(list)
        }
        console.log('data', data)
    }

    //修改商品信息
    const handleProductChangeInfoModal = () => {
        setShowApplyFor(false)
        setCurrentRow(undefined)
        setShopData([])
        setSelectRowList([])
        setSelectedOrderRowKeys([])
        setShowDetailType(null)

        setApprovaType(0)
    }

    const handleCancelShopInfo = () => {
        setEditSelectRow(undefined)
        setEditShopModal(false)
    }

    useEffect(async () => {
        const req: any = {
            SearchParameter: {
                PROVINCE_CODE: currentUser?.ProvinceCode,
                APPROVALROUTE_STATES: "",
                APPROVALROUTE_VALID: 1,
                OPERATION_TYPES: "100200",
            }
        }
        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)

    }, [])

    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-100210",
                                    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={3} onRef={NewApplicationRef} parentRow={currentRow} tableRef={actionRef} onShow={showApplyFor} handleCencel={handleProductChangeInfoModal} currentUser={currentUser} showDetailType={showDetailType}
                InitiateApplication={InitiateApplication} shopData={shopData} handleChangeShopData={setShopData} ApprovalType={ApprovalType} setShowAddShopModal={setShowAddShopModal} setEditSelectRow={setEditSelectRow}
                setEditShopModal={setEditShopModal} setSelectRowList={setSelectRowList} setSelectedOrderRowKeys={setSelectedOrderRowKeys}
            />

            {/* 选择商品 */}
            <SelectShopModal onShow={showAddShopModal} setShowAddShopModal={setShowAddShopModal} setShopData={setShopData} selectRowList={selectRowList} currentUser={currentUser} CommodityData={CommodityData}
                selectedOrderRowKeys={selectedOrderRowKeys} setSelectRowList={setSelectRowList} setSelectedOrderRowKeys={setSelectedOrderRowKeys} formRef={NewApplicationRef} />

            {/* 编辑商品的悬浮框 */}
            <EditShopModal modalType={3} onShow={editShopModal} currentShopRow={editSelectRow} handleCencel={handleCancelShopInfo} currentUser={currentUser} parentRow={currentRow} treeView={treeView} setShopData={setShopData} shopData={shopData} />

        </div >
    )
}

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