import { DownloadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import EditableProTable from '@ant-design/pro-table';

import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import ExportJsonExcel from 'js-export-excel';
import {
  getStockItemList,
  updateStockItem,
  getProductPage,
  getOrgPage,
  getUintList,
  StockInventorySet,
  removeStockItem
} from './service';

//页面 相当于 class
const StockItemManage = () => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  const [dataList, setDataList] = useState([]);

  //机构变量
  const [orgEnum, setOrgEnum] = useState();
  const [orgArray, setOrgArray] = useState([]);

  //物料变量
  const [productEnum, setProductEnum] = useState();
  const [productArray, setProductArray] = useState([]);

  const [uintListEnum, setUintEnum] = useState();

  //初始化数据
  useEffect(() => {
    //初始化物料
    const initProduct = (val) => {
      var data = getProductPage({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.name,
            id: item.id,
          });
          list[item.id] = { text: item.name };
        });

        setProductArray(list2);
        setProductEnum(list);
      });
    };

    //初始化机构
    const initOrg = (val) => {
      var data = getOrgPage({ current: 1, pageSize: 1000 }).then((data) => {
        var list = {};
        let list2 = [];
        data.data.data.forEach((item) => {
          list2.push({
            text: item.name,
            id: item.id,
          });
          list[item.id] = { text: item.name };
        });

        setOrgArray(list2);
        setOrgEnum(list);
      });
    };

    //初始化包装单位
    const initUintList = (val) => {
      var data = getUintList().then((data) => {
        var list = {};
        data.data.forEach((item) => {
          list[item.id] = { text: item.name };
        });
        setUintEnum(list);
      });
    };

    initProduct();
    initOrg();
    initUintList();
  }, []);

  /**
   * 更新节点
   *
   * @param fields
   */
  function handleUpdate(fields) {
    try {
      updateStockItem(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('修改成功');
          actionRef.current.reload();
        } else {
          message.error('修改失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  }

  /**
   * 导出
   */
  function handleExport() {
    const { ReqDetailList } = dataList; // 网络请求命名空间
    const option = {};
    var excelColumns = [];
    columnsR.map((item, index) => {
      if (index > 0 && item.title != "操作") {
        excelColumns.push(item);
      }
    });
    option.fileName = '库存报表';
    option.datas = [
      {
        sheetData: dataList.map((item) => {
          const result = {};
          columnsR.forEach((c, index) => {
            if (index > 0 && item.title != "操作") {
              result[c.dataIndex] = item[c.dataIndex];
            }
          });
          return result;
        }),
        sheetName: '库存报表', // Excel文件名称
        sheetFilter: excelColumns.map((item) => item.dataIndex),
        sheetHeader: excelColumns.map((item) => item.title),
        columnWidths: excelColumns.map(() => 10),
      },
    ];

    const toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }

  /** 国际化配置 */

  const columnsR = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '商品大类',
      hideInSearch: true,
      dataIndex: '',
      editable: false,
    },
    {
      title: '商品小类',
      hideInSearch: true,
      dataIndex: '',
      editable: false,
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      editable: false,
    },
    {
      title: '供应商',
      dataIndex: '',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '品牌',
      hideInSearch: true,
      dataIndex: '',
      editable: false,
    },
    {
      title: '商品规格',
      dataIndex: 'specs',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '库存单位',
      dataIndex: 'uintName',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '上期库存数量',
      dataIndex: 'stockQty',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '入库数量',
      dataIndex: '',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '出库数量',
      dataIndex: '',
      valueType: 'textarea',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '盘点数量',
      dataIndex: 'stockQty',
      valueType: 'textarea',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      }
    },
    {
      title: '报损',
      dataIndex: 'damageCount',
      valueType: 'textarea',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      }
    },
    {
      title: '调拨出库数量',
      dataIndex: 'transferIssueCount',
      valueType: 'textarea',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      }
    },
    {
      title: '调拨入库数量',
      dataIndex: 'transferReceiptCount',
      valueType: 'textarea',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      }
    },
    //验证编辑更新时，输入框是否有值，相当于正则
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          style={{ color: '#78cdd1' }}
          onClick={() => {
            var _a;
            (_a = action.startEditable) === null || _a === void 0 ? void 0 : _a.call(action, record.id);
          }}
        >
          编辑
        </a>
      ]
    }
  ];

  return (
    <PageContainer>
      <EditableProTable
        rowKey="id"
        columns={columnsR}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => handleExport()}>
            <DownloadOutlined /> 导出
          </Button>,
        ]}
        request={async (params) => {
          var stockItemData = [];
          var total = 0;
          await getStockItemList(params).then((r) => {
            stockItemData = r.data.data;
            total = r.data.total;
            setDataList(r.data.data);
          });

          return {
            data: stockItemData,//数据源注入
            success: true,
          }
        }}//获取后台的数据
        value={dataList}//必须要写上，否则更新或者删除时表格数据不会更新
        editable={{
          type: 'multiple',
          onSave: async (rowKey, newData, oldData) => {
            StockInventorySet(newData).then((r) => {
              if (r.data) {
                message.success('修改成功');
              } else {
                message.error('修改失败请重试！');
              }
            });
            console.log(rowKey, newData, oldData);
            //保存时触发 rowKey是每行数据的id,newData是新填写的数据,oldData是老数据，依据业务需求向后台传参。
          },
          onDelete: async (rowKey, data) => {
            removeStockItem(rowKey).then((r) => {
              if (r.data) {
                message.success('删除成功');
              } else {
                message.error('删除失败！');
              }
            });
            console.log(rowKey, data);
            //删除时触发 rowKey是每行数据的id,data是删除的数据，依据业务需求向后台传参。
          }
        }}
        recordCreatorProps={{
          position: 'end',
          record: () => ({
            id: Date.now(),//最好写上，否则控制台报key警告。
          }),
          onClick: () => {
            message.destroy()
          }
        }}//此项配置是新添加一行的按钮配置，详细配置可查看 EditableProTable文档
      />


    </PageContainer>
  );
};

export default StockItemManage;
