import { PlusOutlined } from '@ant-design/icons';
import { Card, Tree, Button, message, Input, Drawer, Divider, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import api from './service';
import {randomString} from '../../../comm'
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  try {
    await api.add(fields).then((r) => {
      if (r.data) {
        message.success('添加成功');
      } else {
        message.error(e.error);
      }
    });
    return true;
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  try {
    await api.update(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.error(e.error);
      }
    });
    return true;
  } catch (error) {
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  if (!selectedRows) return true;
  try {
    await api.removeProduct(selectedRows.map((row) => row.id)).then((r) => {
      if (r.data) {
        message.success('删除成功');
        return true;
      } else {
        message.error(e.error);
      }
    });
    return true;
  } catch (error) {
    message.error('删除失败，请重试');
    return false;
  }
};
const ProductManage = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  /**详情 */
  const [showDetail, setShowDetail] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  const [dicData, setDicData] = useState([]);
  const [dicDataAny, setDicDataAny] = useState([]);
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();
  const [UintList, setUintList] = useState();
  const [TypeList, setTypeList] = useState();
  const [TypeId, setTypeId] = useState('');
  // 监控数据变化
  useEffect(() => {
  
    initUintList();
    initTypeList();
    function intDicData() {
      api.GetDicList('BatchingType').then((r) => {
        var arr = r.data;
        // arr.forEach((element) => {
        //   //element.text = element.remark;
        //  // element.batchingTypeId = element.value;
        // });
        let data = {};
        if (r.succeeded) {
          var list = [];
          arr.forEach((item) => {
            data[item.code] = { text: item.remark };
            list.push({
              batchingType: item.code,
              text: item.remark,
              value: item.code,
              label: item.remark,
            });
          });
          setDicDataAny(data);
          setDicData(list);
        }
      });
    }
    intDicData();
  }, []);
  const initUintList = async (value) => {
    var data = await api.getUintList();
    var list = [];
    if (data.data.length > 0) {
      data.data.forEach((item) => {
        list.push({ stockuint: item.id, text: item.name, value: item.id, label: item.name });
      });
    }
    setUintList(list);
  };
  const initTypeList = async (value) => {
    var data = await api.getTypeList();
    var list = [];
    if (data.data.length > 0) {
      data.data.forEach((item) => {
        list.push({ typeid: item.id, text: item.name, value: item.id, label: item.name });
      });
    }
    setTypeList(list);
  };
  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: 'key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '物料名称',
      dataIndex: 'name',
      ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '物料编码',
      dataIndex: 'code',
      ellipsis: true,
    },
    {
      title: '物料类别',
      dataIndex: 'typeID',
      valueType: 'select',
      hideInSearch: true,
      fieldProps: {
        options: TypeList,
      },
    },
    {
      title: '物料单位',
      dataIndex: 'stockUint',
      valueType: 'select',
      fieldProps: {
        options: UintList,
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => [
        <a
          onClick={() => {
            handleModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          更新
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            api.removeProduct([record.id]).then((r) => {
              if (r.succeeded) {
                message.success('删除成功');
                actionRef.current.reloadAndRest();
              } else {
                message.error(e.error);
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer ost header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="物料列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              var values={code:randomString(4)}
              setStepFormValues(values);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          let UserData = [];
          var total = 0;
          await api.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;
            </div>
          }
        >
          <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
      <CreateForm
        dicData={dicData}
        uintListData={UintList}
        typeListData={TypeList}
        initUintList={initUintList}
        initTypeList={initTypeList}
        onFinish={async (value) => {
          var success = false;
          console.log("value",value)
          setStepFormValues({});
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }

          actionRef.current.reloadAndRest();
        }}
        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 ProductManage;
