/*
 * @Author cclue
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2022-04-28 16:43:35
 * @LastEditors: Please set LastEditors
 * @Description: 商品管理页面 未使用
 * @FilePath: \cloud-platform\src\pages\basicManage\Commdity\list.tsx
 */
import { getFieldEnum, getServerpartOption } from "@/services/options";
import { getTreeSelectOption } from "@/utils/format";
import { PlusOutlined } from "@ant-design/icons";
import ProDescriptions from "@ant-design/pro-descriptions";
import { ModalForm, ProFormDigit, ProFormMoney, ProFormSelect, ProFormSwitch, ProFormText } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable from "@ant-design/pro-table";
import { Form } from "antd";
import { TreeSelect } from "antd";
import { Button, Col, Drawer, message, Popconfirm, Row, Space,Switch } from "antd";
import { useRef, useState, useEffect } from "react";

import type { ProDescriptionsItemProps } from "@ant-design/pro-descriptions";
import type { TreeSelectModel } from "@/utils/format";
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import type { FormInstance } from "antd";
import type { CommdityModel } from './data'
import { getList, delCommdity, getCommodityTypeTree, updateCommodity } from "./service";

import numeral from 'numeral';
import './styles.less'

// 删除商品
const handelDelete = async (commodityid: string) => {
    const hide = message.loading('正在删除...');
    try {
        const result = await delCommdity(commodityid)

        hide();
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Code !== 100}:删除失败`)
            return false
        }
        message.success("删除成功！")
        return true
    } catch (error) {
        hide();
        message.error("删除失败")
        return false
    }
}

// 更新商品
const handleAddUpdate = async (fields: CommdityModel) => {
    const hide = message.loading('正在提交...')

    const result = await updateCommodity(fields)
    hide()
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`)
        return false
    }
    message.success(fields.COMMODITY_ID ? "更新成功！" : "新建成功！")
    return true
}

/**
 * @description: 商品管理组件主体
 * @param {*}
 * @return {*}
 */
const CommdityTable: React.FC = () => {
    const actionRef = useRef<ActionType>()
    const formRef = useRef<FormInstance>()
    const [currentRow, setCurrentRow] = useState<CommdityModel>()
    const [showDetail, setShowDetail] = useState<boolean>()
    const [modalVisible, handleModalVisible] = useState<boolean>()
    const [treeSelectOption, setTreeSelectOption] = useState<TreeSelectModel[]>() // 格式化的商品类别数据 用于树选择
    useEffect(() => {
        async function getTypes() {

            const data = await getCommodityTypeTree() // 获取商品类别数据
            const tree = await getTreeSelectOption({ id: 'value', title: 'label', value: 'value', pId: 'pid' }, data) // 格式化类别数据

            setTreeSelectOption(tree)
        }
        getTypes()
    }, [])

    const columns: ProColumns<CommdityModel>[] = [
        {
            dataIndex: 'COMMODITY_BARCODE',
            title: '条码',
            hideInSearch: true,
        },
        {
            dataIndex: 'COMMODITY_NAME',
            title: '名称',
            hideInSearch: true,
        },
        {
            dataIndex: 'keyword',
            title: '名称/条码',
            hideInDescriptions: true,
            hideInTable: true,
        },

        {
            dataIndex: 'COMMODITY_TYPENAME',
            title: '类别',
            hideInSearch: true,
        },
        {
            title: '所属类别',
            dataIndex: 'COMMODITY_TYPE',
            hideInTable: true,
            hideInDescriptions: true,

            renderFormItem: () => {

                return (
                    <TreeSelect
                        key="selectCate"
                        placeholder="请选择商品类别"
                        dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                        treeDataSimpleMode
                        treeDefaultExpandAll
                        treeData={treeSelectOption}
                    />)
            }
        },
        {
            dataIndex: 'COMMODITY_RETAILPRICE',
            title: '零售价',
            hideInSearch: true,
            render: (_) => {
                return numeral(_).format('0,0.00')
            }
        },
        {
            dataIndex: 'BUSINESSTYPE',
            title: '商品业态',
            hideInTable: true,
            hideInDescriptions: true,
            valueType: 'select',
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' })
            }
        },
        {
            dataIndex: 'BUSINESSTYPE',
            title: '业态',
            hideInSearch: true,
            valueType: 'select',
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' })
            }
        },
        {
            dataIndex: 'COMMODITY_RULE',
            title: '规格',
            hideInSearch: true
        },
        {
            dataIndex: 'COMMODITY_UNIT',
            title: '单位',
            hideInSearch: true
        },
        {
            dataIndex: 'COMMODITY_GRADE',
            title: '质量等级',
            valueType: 'select',
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'COMMODITYGRADE' })
            },
            hideInSearch: true,
            hideInTable: true
        },
        {
            dataIndex: 'COMMODITY_ORI',
            title: '产地',
            hideInSearch: true,
            hideInTable: true
        },
        {
            dataIndex: 'SERVERPART_ID',
            title: '所属服务区',
            valueType: 'select',
            request: async () => {
                return await getServerpartOption()

            }
        },
        {
            dataIndex: 'COMMODITY_STATE',
            title: '状态',
            initialValue: "1",
            valueType: 'select',
            colSize: 1,
            valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' } }
        },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作员',
            hideInTable: true,
            hideInSearch: true
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '更新时间',
            valueType: 'fromNow',
            hideInTable: true,
            hideInSearch: true
        },
        {
            dataIndex: 'option',
            title: '操作',
            valueType: 'option',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a onClick={() => {
                            setCurrentRow(record)
                            setShowDetail(true)
                        }}>查看</a>
                        <a onClick={() => {
                            setCurrentRow({ ...record })
                            handleModalVisible(true)

                        }}>编辑</a>
                        <Popconfirm title="确认删除该商品吗?" onConfirm={async () => {

                            const sucesse = await handelDelete(record.COMMODITY_ID)
                            if (sucesse && actionRef.current) {
                                actionRef.current.reload()
                            }
                        }}>
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ]
    return (
        <PageContainer>
            <ProTable<CommdityModel>
                rowKey="COMMODITY_ID"
                headerTitle="商品列表"
                actionRef={actionRef}
                search={{ span: 6 }}
                request={async (params) => {
                    const { SERVERPART_ID } = params
                    // params.ServerpartId = SERVERPART_ID

                    const data = await getList({ ...params, SortStr: 'COMMODITY_STATE desc' ,ServerpartId: SERVERPART_ID})
                    return data
                }}
                columns={columns}
                toolbar={{
                    actions: [
                        <Button
                            key="new"
                            icon={<PlusOutlined />}
                            type="primary"
                            onClick={() => {
                                handleModalVisible(true)

                            }}
                        >商品</Button>,
                    ]
                }}
                options={false}
            />
            {/* 详情 */}
            <Drawer
                width={600}
                visible={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.COMMODITY_NAME && (
                    <ProDescriptions<CommdityModel>
                        column={2}
                        title={currentRow?.COMMODITY_NAME}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.COMMODITY_ID,
                        }}
                        columns={columns as ProDescriptionsItemProps<CommdityModel>[]}
                    />
                )}
            </Drawer>
            {/* 编辑数据弹框 */}
            <ModalForm<CommdityModel>
                title={currentRow ? '更新商品' : '新建商品'}
                width={1024}
                layout={"horizontal"}
                wrapperCol={{ span: 15 }}
                labelCol={{ span: 6 }}
                formRef={formRef}
                visible={modalVisible}
                autoFocusFirstInput
                modalProps={{
                    onCancel: () => {
                        // console.log('close')
                    },

                }}
                onVisibleChange={(value) => {
                    handleModalVisible(value)
                    if (value) {

                        formRef.current?.setFieldsValue(currentRow || { COMMODITY_STATE: 1, METERINGMETHOD: 1 })
                    } else {
                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }

                }}
                onFinish={async (values) => {

                    let newValue: CommdityModel = { ...values }
                    if (currentRow) { // 编辑数据
                        newValue = { ...values, COMMODITY_ID: currentRow.COMMODITY_ID }
                    }
                    newValue.COMMODITY_STATE = values.COMMODITY_STATE ? 1 : 0
                    newValue.ISBULK = values.ISBULK ? 1 : 0
                    const success = await handleAddUpdate(newValue as CommdityModel);

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        return true
                        
                    }

                    return false;
                }}

            >
                <div className="site-description-title">基础信息</div>
                <Row>
                    <Col span={12} >
                        <ProFormText

                            name="COMMODITY_NAME"
                            label="商品名称"
                            placeholder="请输入名称"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入名称',
                                },
                            ]}
                        /></Col>
                    <Col span={12} >
                        <ProFormDigit
                            disabled={!!((currentRow && currentRow?.COMMODITY_BARCODE !== ''))}

                            name="COMMODITY_BARCODE"
                            label="商品条码"
                            placeholder="请输入（不填则系统自动生成）"

                        />
                    </Col>
                </Row>

                <Row>
                    <Col span={12} >
                        <ProFormText
                            disabled={!!((currentRow && currentRow?.COMMODITY_CODE !== ''))}
                            name="COMMODITY_CODE"
                            label="商品编码"
                            placeholder="请输入商品编码"

                        /></Col>
                    <Col span={12} >
                        <Form.Item
                            name="COMMODITY_TYPE"
                            label="商品类别"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择商品类别',
                                },
                            ]}
                        >
                            <TreeSelect
                                placeholder="请选择商品类别"
                                dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                                treeDefaultExpandAll
                                treeDataSimpleMode
                                treeData={treeSelectOption}
                            />

                        </Form.Item>

                    </Col>
                </Row>
                <Row>
                    <Col span={12} >
                        <ProFormText
                            name="COMMODITY_RULE"
                            label="规格"
                            placeholder="请输入规格"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入商品规格',
                                },
                            ]}
                        />
                        <ProFormText
                            name="COMMODITY_UNIT"
                            label="单位"
                            placeholder="请输入单位"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入商品单位',
                                },
                            ]}
                        />
                    </Col>
                    <Col span={12} >
                        <ProFormSelect
                            request={async () => {
                                return await getServerpartOption()

                            }}
                            name="SERVERPART_ID"
                            label="服务区"
                            placeholder="请选择服务区"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择服务区',
                                },
                            ]}
                        />
                        <ProFormSelect
                            name="COMMODITY_GRADE"
                            label="质量等级"
                            request={async () => {
                                return await getFieldEnum({ FieldExplainField: 'COMMODITYGRADE', notformate: true })
                            }}
                            rules={[
                                {
                                    required: true,
                                    message: '请选择质量等级',
                                },
                            ]}
                        />
                    </Col>

                </Row>
                <Row>
                    <Col span={12} >

                        <ProFormText
                            name="COMMODITY_ORI"
                            label="产地 "
                            placeholder="请输入产地 "
                            rules={[
                                {
                                    required: true,
                                    message: '请输入商品产地',
                                },
                            ]}
                        />
                    </Col>

                    <Col span={12} >
                        <ProFormSelect
                            request={async () => {
                                return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' })

                            }}
                            name="BUSINESSTYPE"
                            label="商品业态"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择商品业态',
                                },
                            ]}
                        />
                    </Col>
                </Row>
                <Row>
                    <Col span={12} >
                         {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                         <Form.Item
                            name="ISBULK"
                            label="是否散装"
                            rules={[
                                {
                                    required: true,
                                    message: '是否散装',
                                },
                            ]}
                        >
                            <Switch
                                checkedChildren="有"
                                unCheckedChildren="无"
                                defaultChecked={currentRow ? !!currentRow.ISBULK : true}
                            />
                        </Form.Item>
                          {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                          <Form.Item
                            name="COMMODITY_STATE"
                            label="是否有效"
                            rules={[
                                {
                                    required: true,
                                    message: '是否无效',
                                },
                            ]}
                        >
                            <Switch
                                checkedChildren="有"
                                unCheckedChildren="无"
                                defaultChecked={currentRow ? !!currentRow.COMMODITY_STATE : true}
                            />
                        </Form.Item>
                        {/* <ProFormSwitch
                            name="ISBULK"
                            label="是否散装"
                            placeholder="是否散装"
                            checkedChildren="是"
                            unCheckedChildren="否"
                            rules={[
                                {
                                    required: true,
                                    message: '是否散装',
                                },
                            ]}
                        />
                        <ProFormSwitch
                            name="COMMODITY_STATE"
                            label="是否有效"
                            checkedChildren="有效"
                            unCheckedChildren="无效"
                            placeholder="是否无效"
                            rules={[
                                {
                                    required: true,
                                    message: '是否有效',
                                },
                            ]}
                        /> */}
                    </Col>
                    <Col span={12} >
                        <ProFormSelect
                            request={async () => {
                                return await getFieldEnum({ FieldExplainField: 'METERINGMETHOD' })
                            }}
                            name="METERINGMETHOD"
                            label="计价方式"

                        />
                    </Col>
                </Row>

                <p className="site-description-title">价格信息</p>
                <Row>
                    <Col span={12} >
                        <ProFormMoney
                            rules={[
                                {
                                    required: true,
                                    message: '请输入商品零售价',
                                },
                            ]}
                            name="COMMODITY_RETAILPRICE"
                            label="零售价" />
                    </Col>


                    <Col span={12} >
                        <ProFormMoney

                            name="COMMODITY_UNIFORMPRICE"
                            label="配货价" />
                    </Col>

                </Row>
                <Row>
                    <Col span={12} >
                        <ProFormMoney
                            name="COMMODITY_PURCHASEPRICE"
                            label="进货价"
                            placeholder="请输入所属单位"
                        />
                    </Col>
                    <Col span={12} >
                        <ProFormMoney

                            name="COMMODITY_MEMBERPRICE"
                            label="会员价"
                            placeholder="请输入所属单位"
                        />
                    </Col>
                </Row>
                <Row>

                    <Col span={12} >
                        <ProFormMoney

                            name="COMMODITY_PROMOTIONPRICE"
                            label="进价优惠" />
                    </Col>
                    <Col span={12} >
                        <ProFormMoney

                            name="COMMODITY_GROUPPRICE"
                            label=" 联销价" />
                    </Col>


                </Row>
            </ModalForm>
        </PageContainer>
    );
}

export default CommdityTable;