import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm,Modal } 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 GoodsAttribute from './components/CreateAttribute';
import {
  goodsType,
  addGoodsType,
  updateGoodsType,
  removeGoodsTypes,
  gettree,
  DeleteGoodsType,
  DeleteGoodsTypes,
} from './service';



const GoodsTypeManage = () => {
  /** 新建/更新窗口的弹窗 */
  const [createformModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [dicData, setDicData] = useState([]);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [treeData, setTreeData] = useState();
  const [GoodsAttributeVisible,setGoodsAttributeVisible]= useState(false);
  /** 国际化修改 */
  useEffect(() => {
   
    intDicData();
  }, []);
  function intDicData() {
    gettree().then((r) => {
      setTreeData(r.data);
    });
  }

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

 const handleUpdate = async (fields) => {
  const hide = message.loading('正在修改');
  try {
    await updateGoodsType({
      id: fields.id,
      name: fields.name,
      sort: fields.sort,
      remark: fields.remark,
      status: fields.status,
      pid:fields.pid
    }).then((r) => {
      if (r.succeeded) {
        message.success('修改成功');
        intDicData();
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

  /**
   * 批量删除
   *
   * @param selectedRows
   */
   
  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    await DeleteGoodsTypes(selectedRows.map((row) => row.id)).then((r) => {
      if (r.succeeded) {
        message.success('删除成功');
        actionRef.current.reloadAndRest();
        intDicData()
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  };
  const onGoodsAttributeCancel=()=>{
    setGoodsAttributeVisible(false);
    setCurrentRow({});
  }
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'textarea',
      ellipsis: true,
    },

    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
    
        <a
          key="config"
          onClick={() => {
            if(record.pid=="0"){
              record.pid=null;
            }
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        
        <a
          key="config"
          onClick={() => {
            setGoodsAttributeVisible(true);
            setCurrentRow(record);
          }}
        >
          添加属性
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            await DeleteGoodsType(record.id).then((r) => {
              if (r.succeeded) {
                message.success('删除成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(r.errors);
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var goodsData = [];
          var total = 0;
          await goodsType(params).then((r) => {
            goodsData = r.data.data;
            goodsData.forEach((x) => {
              x.status = x.status.toString();
            });
            total = r.data.total;
          });
          return {
            data: goodsData,
            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.id, 0)} 万
              </span> */}
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        treeDatas={treeData
          // [
          //   {
          //     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);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createformModalVisible={createformModalVisible}
        values={currentRow || {}}
      />
      <Modal  title={'属性'}
      width={1040}
      visible={GoodsAttributeVisible}
      bodyStyle={{ padding: '32px 40px 1px 48px' }}
      footer={null}
      onCancel={() => {
        onGoodsAttributeCancel();
      }}
      destroyOnClose>
        <GoodsAttribute currentRow={currentRow}/>
      </Modal>

      <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 GoodsTypeManage;
