import { PlusOutlined } from '@ant-design/icons';
import { Card, Tree, Button, message, Input, Drawer, Divider } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import { add, edit, getdetail, getlist, getpage, gettree, orgdelete } from './service';
import { history } from 'umi';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  try {
    var r = await add({ ...fields });
    if (!r.succeeded) {
      message.error(r.errors);
      hide();
      return false;
    }
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    var r = await edit({ ...fields });
    if (!r.succeeded) {
      message.error(r.errors);
      hide();
      return false;
    }
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await orgdelete({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const TableList = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  /** 分布更新窗口的弹窗 */
  const [updateRoleModalVisible, handleUpdateRoleModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState();
  /**详情 */
  const [showDetail, setShowDetail] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  const [treeData, setTreeData] = useState();
  const [Pid, setKey] = useState();
  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '组织名称',
      dataIndex: 'name',
    },
    {
      title: '组织编码',
      dataIndex: 'code',
    },
    {
      title: '组织类型',
      dataIndex: 'type',
      valueEnum: {
        0: {
          text: '机构',
        },
        1: {
          text: '配送中心',
        },
        2: {
          text: '直营店',
        },
        3: {
          text: '加盟店',
        },
      },
    },
    {
      title: '电话',
      dataIndex: 'tel',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'x',
      valueType: 'option',
      render: (_, record) => {
        let node = <a key="primary"></a>;

        if (record.type >= 2) {
          node = (
            <a
              key="primary2"
              onClick={() => {
                history.push({
                  pathname: '/sys/storemanage',
                  query: {
                    isAdd: false,
                    values: record.id
                  },
                });
                // handleModalVisible(true);
                // setStepFormValues(record);
              }}
            >
              店铺管理
            </a>
          );
        }
        return [
          <a
            key="primary3"
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
            }}
          >
            {' '}
            修改
          </a>,
          node,
        ];
      },
    },
  ];
  useEffect(() => {
    function initfranchiseeType() {
      gettree().then((r) => {
        setTreeData(r.data);
      });
    }
    initfranchiseeType();
  }, []);
  return (
    <PageContainer>
      <ProTable
        headerTitle="组织列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Card title="机构部门">
              <Tree defaultExpandAll={true} onSelect={(e) => setKey(e[0])} treeData={treeData} />
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary1"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        params={{
          Pid,
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;
          //添加机构组织
          await getpage(params).then((r) => {
            UserData = r.data.data;
            total = r.data.total;
          });
          return {
            data: UserData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      // rowSelection={{
      //   onChange: (_, selectedRows) => {
      //    // setSelectedRows(selectedRows);
      //   },
      // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <CreateForm
        treeDatas={
          [
            {
              key: '0',
              parentId: '0',
              title: '顶级',
              value: '0',
              children: treeData,
            },
          ] || [
            {
              id: '0',
              parentId: '0',
              title: '顶级',
              value: '0',
              children: [],
            },
          ]
        }
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              gettree().then((r) => {
                setTreeData(r.data);
              });
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
