import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Card, Col, message, Row, Switch } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { Access, useAccess } from '@umijs/max';
import Constants from '@/constants';
import { addSpecificationItemUsingPost, addSpecificationUsingPost, changeSpecificationItemStateUsingPost, getSpecificationItemListUsingGet, specificationListUsingGet } from '@/services/pop-b2b2c/pbcSpecificationController';
import { PlusCircleFilled } from '@ant-design/icons';
import UpdateForm from './components/UpdateForm';
import UpdateItemForm from './components/UpdateItemForm';

/**
 * 查询表格
 * @param param0
 */
const fetchData = async (params: any) => {
  const msg = await getSpecificationItemListUsingGet(params);
  return {
    data: msg.data || [],
    success: msg.retcode,
  } as any;
};

const handleUpdateState = async (id: number, state: number) => {
  const hide = message.loading('正在保存');
  if (!id) return false;
  try {
    const msg = await changeSpecificationItemStateUsingPost({ pbcId: id, pbcState: state });
    hide();
    if (msg.retcode) {
      message.success(!id ? '新增成功！' : '保存成功！');
      return true;
    }
    message.error(msg.retmsg);
    return false;
  } catch (error) {
    hide();
    message.error(!id ? '新增失败，请重试！' : '保存失败，请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: API.PbcSpecification) => {
  const hide = message.loading('正在保存');

  try {
    const msg = await addSpecificationUsingPost({ ...fields });
    hide();
    if (msg.retcode) {
      message.success(!fields.pbcId ? '添加成功' : '保存成功');
      return true;
    }
    message.error(msg.retmsg);
    return false;
  } catch (error) {
    hide();
    message.error(!fields.pbcId ? '添加失败请重试！' : '保存失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */
const handleItemUpdate = async (fields: API.PbcCommonDataValue) => {
  const hide = message.loading('正在保存');

  try {
    const msg = await addSpecificationItemUsingPost({ ...fields });
    hide();
    if (msg.retcode) {
      message.success(!fields.pbcId ? '添加成功' : '保存成功');
      return true;
    }
    message.error(msg.retmsg);
    return false;
  } catch (error) {
    hide();
    message.error(!fields.pbcId ? '添加失败请重试！' : '保存失败请重试！');
    return false;
  }
};


const Welcome: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const access: any = useAccess();

  const [specList, setSpecList] = useState<API.PbcSpecification[]>([])
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [updateItemModalVisible, handleUpdateItemModalVisible] = useState<boolean>(false);
  const [specificationId, setSpecificationId] = useState<number>()

  const columns: ProColumns<API.PbcCommonDataValue>[] = [
    {
      title: 'ID',
      dataIndex: 'pbcId',
    },
    {
      title: '名称',
      dataIndex: 'pbcSystemValue',
    },
    {
      title: '最后操作人',
      dataIndex: 'pbcUpdateByUserName',
    },
    {
      title: '最后操作时间',
      dataIndex: 'pbcUpdateAt',
    },
    {
      title: '状态',
      dataIndex: 'pbcState',
      valueType: 'select',
      valueEnum: Constants.state,
      render: (_, record) => {
        return (
          <Access key="switch" accessible={access.dictionaryUpdate}>
            <Switch
              checked={record.pbcState === 1}
              onChange={async (value) => {
                const success = await handleUpdateState(record.pbcId || 0, value ? 1 : 2);

                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
            />
          </Access>
        );
      },
    },
  ]

  const getData = () => {
    specificationListUsingGet().then(res => {
      if (res.retcode && res.data) {
        setSpecList(res.data)
      }
    })
  }

  useEffect(() => {
    getData()
  }, [])

  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
    >
      <Row gutter={16}>
        <Col span={4}>
          <Card title="规格" bodyStyle={{ maxHeight: 'calc(100vh - 175px)', overflowY: 'auto' }} bordered={false} extra={
            <Access accessible={access.dictionaryAdd}><PlusCircleFilled style={{ color: '#1890ff', fontSize: 22 }} onClick={() => {
              handleUpdateModalVisible(true)
            }} /></Access>
          }>
            {specList.map(e => <p key={e.pbcId}
              style={{ padding: 10, margin: 0, backgroundColor: specificationId === e.pbcId ? '#1890ff' : undefined, color: specificationId === e.pbcId ? '#fff' : undefined }} onClick={() => {
              setSpecificationId(e.pbcId)
            }}>{e.pbcSystemName}</p>)}
          </Card>
        </Col>
        <Col span={20}>
          <Card title="规格项" bordered={false} extra={
            <Access accessible={access.dictionaryAdd}><PlusCircleFilled style={{ color: '#1890ff', fontSize: 22 }} onClick={() => {
              const index = specList.findIndex(e => e.pbcId === specificationId)
              if (!specificationId) {
                message.warning("请选择规格")
              } else if (index >= 0 && specList[index].pbcSystemInputType === 'text') {
                message.warning("所选规格为文本框，不能新增规格项")
              } else {
                handleUpdateItemModalVisible(true)
              }
            }} /></Access>
          }>
            <ProTable
              request={fetchData}
              actionRef={actionRef}
              bordered
              size='small'
              rowKey="pbcId"
              params={{ specificationId }}
              manualRequest={true}
              columns={columns}
              search={false}
              options={false}
              scroll={{
                y: 'calc(100vh - 280px)',
              }}
              toolBarRender={() => []}
              pagination={false}
            />
          </Card>
        </Col>
      </Row>
      <UpdateForm
        onSubmit={async (value: any) => {
          const success = await handleUpdate(value);

          if (success) {
            handleUpdateModalVisible(false);
            getData()
          }
        }}
        onCancel={() => {
          message.destroy();
          handleUpdateModalVisible(false);
        }}
        updateModalVisible={updateModalVisible}
      />
      <UpdateItemForm
        onSubmit={async (value: any) => {
          const success = await handleItemUpdate({...value, pbcSpecificationId: specificationId});

          if (success) {
            handleUpdateItemModalVisible(false);
            actionRef.current?.reload()
          }
        }}
        onCancel={() => {
          message.destroy();
          handleUpdateItemModalVisible(false);
        }}
        updateModalVisible={updateItemModalVisible}
      />
    </PageContainer>
  );
};

export default Welcome;
