import { PlusOutlined } from '@ant-design/icons';
import { Checkbox, Modal, Space, Tag, Button, message, Input, Drawer, Popconfirm, Spin } 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 moment from 'moment';
import { page, GetOrgList, enable, disable, Delete, DeleteSubset, Update, purchaseorderentrylist } from './services';
import CreateForm from './components/CreateForm';
import { add, GetSupplierList, getpurchaseorderinfo, getproducttypelist, getbatchinglist,getuintlist } from './services';
const key = 'message';
const purchaseOrder = () => {
  const actionRef = useRef();
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, SetCreateModalVisible] = useState(false);
  const formRef = useRef();
  const [currentRow, setCurrentRow] = useState({});
  // 显示控制
  const [modalVisit, setModalVisit] = useState(false);

  const [itemType, setItemType] = useState(false);//物料类型

  const [batchinglist, setBatchinglist] = useState(false);//物料

  const [uint, setUint] = useState(false);//物料


  useEffect(() => {
    const initData = async (value) => {
      var data = await getproducttypelist();
      setItemType(data.data);

      var data1 = await getbatchinglist();
      setBatchinglist(data1.data);

      var data2 = await getuintlist();
      setUint(data2.data);
    };

    initData();
  }, []);



  const purchaseorderinfo = async (value) => {
    var data = await getpurchaseorderinfo(value);
    formRef?.current?.setFieldsValue(data.data);
  }

//停用
const handleDisable = async (fields) => {
  message.loading(`正在拒绝...`, key);
  try {
    await disable(fields).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('拒绝成功');
      } else {
        message.error(JSON.stringify(r.errors));
      }
    });
    //刷新数据
    actionRef.current.reload();
    return true;
  } catch (error) {
    message.destroy(key);
    message.error('操作失败请重试！');
    return false;
  }
};

//启用
const handleEnable = async (fields) => {
  message.loading(`正在通过...`, key);
  try {
    await enable(fields).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.success('通过成功');
      } else {
        message.error(JSON.stringify(r.errors));
      }
    });

    //刷新数据
   // actionRef.current.reload();
    return true;
  } catch (error) {
    message.destroy(key);
    message.error('操作失败请重试！');
    return false;
  }

};


//删除（支持批量删除）
const handleRemove = async (value) => {
  message.loading('正在删除...', key);
  try {
    let ids = [];
    value.forEach((item) => {
      ids.push(item.id);
    });
    await Delete(JSON.stringify(ids)).then((r) => {
      message.destroy(key);
      if (r.data) {
        message.destroy(key);
        message.success('删除成功');
      } else {
        message.error('删除失败请重试！');
      }
    });
    //刷新数据
    actionRef.current.reload();
    return true;
  } catch (error) {
    message.destroy(key);
    message.error('删除失败请重试！');
    return false;
  }
};


  /** 国际化配置 */
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '单号',
      dataIndex: 'shelfNo',
      width: 170,
    },
    {
      title: '收货人',
      dataIndex: 'receivingUser',
      width: 80,
    },
    {
      title: '收货人电话',
      dataIndex: 'receivingTel',
      width: 100,
    },
    {
      title: '收货地址',
      dataIndex: 'receivingAddress',
    },
    {
      title: '是否审核',
      dataIndex: 'approveFlag',
      width: 80,
      valueEnum: {
        false: {
          text: '未审核',
          status: 'Processing',
        },
        true: {
          text: '已审核',
          status: 'Success',
        },
      },
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      width: 80,
      valueEnum: {
        1: {
          text: '拒绝',
          status: 'Error',
        },
        0: {
          text: '通过',
          status: 'Success',
        },
      },
    },
    {
      title: '审核人',
      dataIndex: 'approveOperId_Val',
      width: 80,
      valueType: 'textarea',
    },
    {
      title: '审核时间',
      dataIndex: 'approveDate',
      width: 120,
      valueType: 'date',
    },
    {
      title: '结果',
      dataIndex: 'finish',
      width: 80,
      valueEnum: {
        false: {
          text: '配送中',
          status: 'Processing',
        },
        true: {
          text: '完结',
          status: 'Success',
        },
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      width: 200,
      render: (_, record) => {
        let template = [

          <a
            key="primary"
            type="primary"
            disabled={record.approveFlag}
            style={{ pointerEvents: record.approveFlag ? 'none' : 'auto' }}
            onClick={() => {
              handleEnable(record.id);
            }}
          >
            通过
          </a>,
          <a
            key="primary"
            type="primary"
            disabled={record.approveFlag}
            style={{ pointerEvents: record.approveFlag ? 'none' : 'auto' }}
            onClick={() => {
              handleDisable(record.id);
            }}
          >
            拒绝
          </a>, <a
            key="primary"
            type="primary"
            disabled={record.approveFlag}
            style={{ pointerEvents: record.approveFlag ? 'none' : 'auto' }}
            onClick={async () => {
              setModalVisit(true);
              purchaseorderinfo(record.shelfNo);
            }}
          >
            修改
          </a>,
          <Popconfirm
            type="primary"
            key="primary"
            title="确认删除吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleRemove([record]);
            }}
            onCancel={() => { }}
          >
            <a
              disabled={record.approveFlag}
              style={{ pointerEvents: record.approveFlag ? 'none' : 'auto' }}
              href="#">删除</a>
          </Popconfirm>,
        ];
        return template;
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="采购信息"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => {
            setModalVisit(true);
            purchaseorderinfo("%20");

          }}>
            <PlusOutlined /> 新增
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await page(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />

      {/* ---------新增---------- */}
      <CreateForm
      uint={uint}
      setModalVisit={setModalVisit}
        batchinglist={batchinglist}
        itemType={itemType}
        actionRef={actionRef}
        modalVisit={modalVisit}
        setModalVisit={setModalVisit}
        formRef={formRef}
        onClose={() => {
          setModalVisit(false);
        }}
      />
    </PageContainer>
  );
};

export default purchaseOrder;
