import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Popconfirm } 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 CreateAttribute from './components/CreateAttribute';
import {
    getgoodsattributepage,
    addgoodsattribute,
    deletegoodsattribute,
    gettree,
    addgoodsattributevalue,
    getbomtypepage,
    
} from './service';



const goodsattribute = (props) => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createattrModalVisible, handleMattrodalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [goodstypeData, setGoodstypeData] = useState([]);
  const [attributeid, setAttributeid] = useState('');
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [treeData, setTreeData] = useState();
  /** 国际化修改 */
  useEffect(() => {

    intDicData();
  }, []);
  function intDicData() {
    gettree().then((r) => {
      setTreeData(r.data);
    });
  }

  /**
   * 批量删除
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    await deletegoodsattribute(selectedRows.map((row) => row.id)).then((r) => {
      if (r.succeeded) {
        message.success('删除成功');
        actionRef.current.reloadAndRest();
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  };
  /**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  try {
    await addgoodsattribute(JSON.stringify(fields)).then((r) => {
      if (r.succeeded) {
        message.success('添加成功');
        actionRef.current.reloadAndRest();
      } 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 addgoodsattribute({
      id: fields.id,
      AttributeName: fields.attributeName,
      goodsTypeId: fields.goodsTypeId,
      Sort: fields.sort,
    }).then((r) => {
      if (r.succeeded) {
        message.success('修改成功');
        actionRef.current.reloadAndRest();
      } else {
        message.error(r.errors);
      }
    });
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
  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: 'attributeName',
      valueType: 'textarea',
      ellipsis: true,
    },

    // {
    //   title: '商品类型',
    //   dataIndex: 'goodsTypeName',
    //   valueType: 'treeSelect',
    //   fieldProps: {
    //     showSearch:true,
    //     allowClear:true,
    //     options: treeData
    //   },
    // },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        // <a
        //   key="state"
        //   onClick={async () => {
        //     setAttributeid(record.id);
        //     handleMattrodalVisible(true);
        //     setCurrentRow(record);
           
        //   }}
        // >
        //   添加属性值
        // </a>,
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="删除属性后会将属性的值一起删除，确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={async () => {
            await deletegoodsattribute([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 getgoodsattributepage(params).then((r) => {
            goodsData = r.data.data;
            goodsData.forEach((x) => {
              if(x.goodsTypeId!=null){
                x.goodsTypeId =x.goodsTypeId.split(",");
              }
             
            });
            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
          }
        onFinish={async (value) => {
          console.log(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);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
      <CreateAttribute
  
      onFinish={async (value) => {
        console.log("value",value)
        console.log("props.currentRow",props.currentRow)
        value.goodsTypeId=props.currentRow.id;
        var data=value.map(x=>{
          x.GoodsAttributeId=currentRow.id;
          return x;
        })
        await addgoodsattributevalue(data).then(r=>{
          if(r.data){
            message.success('保存成功');
            handleMattrodalVisible(false);
            actionRef.current.reloadAndRest();
          }else{
            message.error("保存失败");
          }
        })
      }}
      onCancel={async (value) => {
        setAttributeid(undefined);
            handleMattrodalVisible(false);
            setCurrentRow(undefined);
      }}
      attributeid={attributeid}
     
      createattrModalVisible={createattrModalVisible}
      />
    </PageContainer>
  );
};

export default goodsattribute;
