import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import DetailPro from '@/components/DetailPro';
import EditTable from '@/components/InitForm/EditTable';
import { Button } from 'antd';

function Outstore(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
      open: false,
    }),
    [activeTabKey, setactiveTabKey] = useState('1');
  const [value, setvalue] = useState([]);

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  const detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          type: 'link',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: '详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            doFetch({
              url: '/sparepart/outWarehouseTask/queryByBeforeOut',
              params: { id: row?.id },
            }).then((res) => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: row,
                title: '出库',
                val: 'only',
                submitdata: res?.data?.data?.taskSpareList ?? [],
              }));
            });
          },
        }}
      >
        出库
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否关单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => {
            run({ url: '/sparepart/outWarehouseTask/shut', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        关单
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.columns;
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [
        defpath?.enabledetail && detail(text, row, _, action),
        defpath?.enableedit && edit(text, row, _, action),
        defpath?.enabledelete && remove(text, row, _, action),
      ],
    });
  }, [activeTabKey]);

  const pathconfig = useMemo(() => {
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defpath;
  }, [activeTabKey]);

  console.log(value);

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">出库管理</h3>}
        columns={columns}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        actionRef={actionRef}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: null,
                title: '新增',
                val: 'add',
              }));
            },
          },
        }}
        tabList={getcolumns()}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          setactiveTabKey(key);
        }}
      />

      <DrawerPro
        fields={columns}
        detailpath={pathconfig?.detail || null}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={(vals) => {
          const taskSpareList = vals?.taskSpareList?.map?.((it, i) => {
            return {
              spareStockId: it?.id,
              operateNum: it?.operateNum,
            };
          });
          if (drawer?.val == 'add') {
            run({ url: pathconfig?.add || '/add', params: { ...vals, taskSpareList } });
          } else if (drawer?.val == 'edit') {
            run({
              url: pathconfig?.edit || '/edit',
              params: { ...vals, id: drawer?.item?.id, taskSpareList },
            });
          }
        }}
      >
        {drawer?.val == 'only' && (
          <div>
            <DetailPro
              detailpath={pathconfig?.detail || null}
              params={{ id: drawer?.item?.id }}
              fields={columns?.filter(
                (it) => !['details', 'taskSpareList'].includes(it?.key) && it.valueType != 'option',
              )}
            />
            <AutoTable
              columns={[
                {
                  title: '备件料号',
                  dataIndex: 'sparePartNo',
                  key: 'sparePartNo',
                },
                {
                  title: '备件名称',
                  dataIndex: 'sparePartName',
                  key: 'sparePartName',
                },
                {
                  title: '库存单位',
                  dataIndex: 'unit',
                  key: 'unit',
                },
                {
                  title: '出库数量',
                  dataIndex: 'operateNum',
                  key: 'operateNum',
                },
                {
                  title: '未下架数量',
                  dataIndex: 'outNum',
                  key: 'outNum',
                },
              ]}
              pagetitle="备件信息"
              dataSource={drawer?.submitdata}
              expandable={{
                expandedRowRender: (record) => {
                  return (
                    <div style={{ padding: '4px 4px 4px 36px', backgroundColor: '#cccccc' }}>
                      <EditTable
                        resizeable={false}
                        alwaysShowAlert={false}
                        tableAlertRender={false}
                        tableAlertOptionRender={false}
                        columns={[
                          {
                            title: '供应商编号',
                            dataIndex: 'supplierNo',
                            key: 'supplierNo',
                            editable: false,
                          },
                          {
                            title: '供应商名称',
                            dataIndex: 'supplierName',
                            key: 'supplierName',
                            editable: false,
                          },
                          {
                            title: '库存数量',
                            dataIndex: 'actualStock',
                            key: 'actualStock',
                            editable: false,
                          },
                          {
                            title: '下架数量',
                            dataIndex: 'operateNum',
                            key: 'operateNum',
                            valueType: 'digit',
                            fieldProps: {
                              precision: 3,
                            },
                          },
                        ]}
                        dataSource={record?.spareSupplierStockList ?? []}
                        rowSelection={{
                          columnWidth: 44,
                          preserveSelectedRowKeys: true,
                          selectedRowKeys:
                            value &&
                            value
                              ?.filter?.((it) => it?.id == record.id)[0]
                              ?.taskSpareSupplierList?.map?.((it) => it?.spareSupplierStockId),
                          onChange: (selectedKeys, selectedRows) => {
                            const curval =
                              value?.filter?.((it) => it?.id == record.id)[0]
                                ?.taskSpareSupplierList ?? [];

                            const rowkeylist = curval
                              ? curval?.map((it) => it?.spareSupplierStockId)
                              : [];

                            const newValue = selectedRows?.map((its) => {
                              if (rowkeylist.includes(its?.id)) {
                                return curval.filter(
                                  (it) => it?.spareSupplierStockId == its?.id,
                                )[0];
                              } else {
                                return {
                                  spareSupplierStockId: its.id,
                                  operateNum: its.operateNum,
                                };
                              }
                            });
                            console.log(newValue);
                            let nvalue = value ? [...value] : [];
                            if (value && value.some((it) => it.id == record?.id)) {
                              nvalue = value?.map((it, i) => {
                                if (it.id == record.id) {
                                  it.taskSpareSupplierList = newValue;
                                }
                                return it;
                              });
                            } else {
                              nvalue.push({
                                id: record.id,
                                taskSpareSupplierList: newValue,
                              });
                            }

                            setvalue(nvalue);
                          },
                        }}
                        editable={{
                          onValuesChange: (rower, recordList) => {
                            const curval =
                              value?.filter?.((it) => it?.id == record.id)[0]
                                ?.taskSpareSupplierList ?? [];
                            const newValue = curval?.map((its) => {
                              if (its?.spareSupplierStockId == rower?.id) {
                                return {
                                  spareSupplierStockId: rower.id,
                                  operateNum: rower.operateNum,
                                };
                              } else {
                                return its;
                              }
                            });
                            console.log(newValue);
                            let nvalue = value ? [...value] : [];
                            if (value && value.some((it) => it.id == record?.id)) {
                              nvalue = value?.map((it, i) => {
                                if (it.id == record.id) {
                                  it.taskSpareSupplierList = newValue;
                                }
                                return it;
                              });
                            } else {
                              nvalue.push({
                                id: record.id,
                                taskSpareSupplierList: newValue,
                              });
                            }
                            setvalue(nvalue);
                          },
                        }}
                      />
                    </div>
                  );
                },
              }}
            />
            <Button
              style={{ marginTop: 12 }}
              type="primary"
              onClick={() => {
                run({
                  url: '/sparepart/outWarehouseTask/OutWarehouse',
                  params: { id: drawer?.item?.id, taskSpareList: value },
                });
              }}
            >
              出库
            </Button>
          </div>
        )}
      </DrawerPro>
    </div>
  );
}

export default Outstore;
