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

/**
 * 添加节点
 *
 * @param fields
 */

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

const handleUpdate = async (fields) => {
  try {
    await api.updateProduct(fields).then((r) => {
      if (r.data) {
        message.success('修改成功');
      } else {
        message.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('删除失败，请重试');
      }
    });
    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();
  // 监控数据变化
  useEffect(() => {
    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);
    };
    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 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: 'specs',
    },
    {
      title: '成本价',
      dataIndex: 'price',
    },
    {
      title: '净料率(%)',
      dataIndex: 'netrecovery',
    },
    {
      title: '物料属性',
      dataIndex: 'aittribute',
      valueEnum: {
        0: {
          text: '成品',
        },
        1: {
          text: '半成品',
        },
        2: {
          text: '易耗品',
        },
      },
    },
    {
      title: '物料类别',
      dataIndex: 'typeID',
      valueType: 'select',
      fieldProps: {
        options: TypeList,
      },
    },
    {
      title: '库存单位',
      dataIndex: 'stockUint',
      valueType: 'select',
      fieldProps: {
        options: UintList,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '停用',
          status: 'Success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          onClick={() => {
            handleModalVisible(true);
            setStepFormValues(record);
          }}
        >
          {' '}
          更新
        </a>,
        <a
          key="primary"
          onClick={() => {
            record.status = record.status == 0 ? 1 : 0;
            api.updateStatus(record).then((r) => {
              if (r.data) {
                actionRef.current.reload();
              }
            });
          }}
        >
          {' '}
          {record.status == 0 ? '停用' : '启用'}
        </a>,
        <Popconfirm
          type="primary"
          key="primary"
          title="确认删除吗？"
          okText="是"
          cancelText="否"
          onConfirm={() => {
            api.removeProduct([record]).then((r) => {
              if (r.data) {
                message.success('删除成功，即将刷新');
                actionRef.current.reload();
              } else {
                message.error('删除失败，请重试');
              }
            });
          }}
          onCancel={() => {}}
        >
          <a href="#">删除</a>
        </Popconfirm>,
        //   <TableDropdown
        //   key="actionGroup"
        //   onSelect={(option) => {
        //     if (option === 'resetPwd') {
        //       Modal.confirm({
        //         title: '重置密码',
        //         icon: <ExclamationCircleOutlined />,
        //         content: '是否确认重置密码',
        //         okText: '确认',
        //         cancelText: '取消',
        //         onOk() {
        //           console.log('OK', record);
        //         },
        //       });
        //     } else if (option === 'grantRole') {
        //       Modal.confirm({
        //         title: 'Confirm',
        //         icon: <ExclamationCircleOutlined />,
        //         content: 'Bla bla ...',
        //         okText: '确认',
        //         cancelText: '取消',
        //       });
        //     } else if (option === 'grantData') {
        //       Modal.confirm({
        //         title: 'Confirm',
        //         icon: <ExclamationCircleOutlined />,
        //         content: 'Bla bla ...',
        //         okText: '确认',
        //         cancelText: '取消',
        //       });
        //     } else if (option === 'delete') {
        //       Modal.confirm({
        //         title: '删除用户',
        //         icon: <ExclamationCircleOutlined />,
        //         content: '是否确认删除用户',
        //         okText: '确认',
        //         cancelText: '取消',
        //       });
        //     }
        //   }}
        //   menus={[
        //     { key: 'adduint', name: '添加一品多单位' },
        //     { key: 'grantRole', name: '新增供货商' },
        //     { key: 'delete', name: '删除' },
        //   ]}
        // />
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="物料列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              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}
        onFinish={async (value) => {
          var success = false;

          setStepFormValues({});
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);

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

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