import { CheckOutlined, 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 { getUintList, getTypeList, add, getPage, approved, getEntry } from './services';
import { gettree } from '../../../sys/org/service';
/**
 * 现在收货
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await add({ ...fields }).then((r) => {
      if (!r.succeeded) {
        return false;
      }
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
const DeliveryCheck = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [UintList, setUintList] = useState();
  const [TypeList, setTypeList] = useState();
  const [OrgList, setOrgList] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);
  useEffect(() => {
    const initUintList = async (value) => {
      var data = await 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 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);
    };
    function initOrgList() {
      gettree().then((r) => {
        setOrgList(r.data);
        let list = {};
        formateData(r.data);
        function formateData(datas) {
          for (var i in datas) {
            list[datas[i]['value']] = { text: datas[i]['title'] };
            if (datas[i].children) {
              formateData(datas[i].children);
            }
          }
        }
        setOrgListArray(list);
      });
    }
    initOrgList();
    initUintList();
    initTypeList();
  }, []);


  const getEntryInfo = async (value) => {
    var data = await getEntry(value);
    debugger
    var list = currentRow;
    list.sub = data.data;
    setCurrentRow(list);
  }
  const handleRemoveSingle= async (value) =>
  {


  }



  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: 'sheetId',
      hideInForm: true,
    },
    {
      title: '收货机构',
      dataIndex: 'orgId',
      valueEnum: OrgListArray,
    },
    {
      title: '制单人',
      dataIndex: 'createByName',
    },
    {
      title: '审核人',
      dataIndex: 'approveByName',
    },
    {
      title: '制单日期',
      sorter: true,
      dataIndex: 'operDate',
      valueType: 'date',
    },
    {
      title: '审核日期',
      sorter: true,
      dataIndex: 'approveAt',
      valueType: 'date',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.isApprove === 0 && (
          <a
            key="config"
            type="primary"
            onClick={async () => {
              var data = await getEntry(record.id);
              if (data.data.data.length>0) {
                record.sub=data.data.data;
              }
              setCurrentRow(record);
              record?.startEditable?.(record.id);

              handleModalVisible(true);
            }}
          >
            修改
          </a>
        ),
        record.isApprove === 0 && (
          <a
            key="config"
            type="primary"
            onClick={() => {
              message.loading('正在审核！');
              try {
                approved({ Id: record.id });
                message.success('审核完成！');
              } catch (error) {
                console.log(error);
                message.error('正在审核失败请重试！');
              }
              actionRef.current.reload();
            }}
          >
            审核
          </a>
        ),
        record.isApprove === 0 && (
          <Popconfirm
            type="primary"
            key="primary"
            title="确认删除吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleRemoveSingle(record.id);
            }}
            onCancel={() => { }}
          >
            <a href="#">删除</a>
          </Popconfirm>
        ),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="收货单"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => {setCurrentRow({}); handleModalVisible(true)}}>
            <PlusOutlined /> 新增
          </Button>,
        ]}
        request={async (params) => {
          var Data = [];
          var total = 0;
          await getPage(params).then((r) => {
            Data = r.data.data;
            total = r.data.total;
          });
          return {
            data: Data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
      />
      {/*库存调整(新增，修改) */}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          success = await handleAdd(value);
          // }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
        typeList={TypeList}
        uintList={UintList}
        OrgData={OrgList}
      />
    </PageContainer>
  );
};

export default DeliveryCheck;
