import { doFetch } from '@/utils/doFetch';
import React, { useState, useEffect, useForceUpdate } from 'react';
import AutoTable from '../../AutoTable/mtable';
import EditTable from '../EditTable';

function Expandables({ value = [], onChange, item }) {
  const [allDatasource, setallDatasource] = useState({});
  const [nvalue, setnvalue] = useState([]);
  return (
    <div>
      <AutoTable
        columns={item?.columns}
        path={item?.path}
        extraparams={item?.extraparams}
        expandable={{
          expandRowByClick: true,
          onExpand: (expanded, record) => {
            if (!expanded) return;
            //找到value中当前展开的值
            let curvalue = value
              ? value.filter((it) => it.lifePieceAccountId == record.id)?.[0]
              : {};
            //value中的list

            let curvalist = curvalue?.lineStockUseList ?? [];
            doFetch({ url: item.expandablePath, params: { lifePieceAccountId: record.id } }).then(
              (res) => {
                //展开接口返回的结果
                let curDatasource = res?.data?.dataList ?? [];
                //组合数据
                let result = curDatasource?.map((it) => {
                  const itemval =
                    curvalist?.filter?.((item) => item.lineStockId == it.id)?.[0] ?? false;
                  if (itemval) {
                    it.operateNum = itemval.operateNum;
                  }
                  return it;
                });

                setallDatasource((s) => ({
                  ...s,
                  [record.id]: result,
                }));
              },
            );
          },
          expandedRowRender: (record) => {
            let curvalue = value
              ? value.filter((it) => it.lifePieceAccountId == record.id)?.[0]
              : {};
            // console.log('nvalue', nvalue);
            // console.log('record', record);
            // console.log('allDatasource:', allDatasource);
            // console.log(
            //   'defaultvalue:',
            //   nvalue?.filter((it) => it.lifePieceAccountId == record.id)?.[0]?.lineStockUseList,
            // );
            return (
              <>
                <EditTable
                  key={nvalue
                    .filter((it) => it.lifePieceAccountId == record.id)?.[0]
                    ?.lineStockUseList.map((it) => it.lineStockId)}
                  resizeable={false}
                  alwaysShowAlert={false}
                  tableAlertRender={false}
                  tableAlertOptionRender={false}
                  defaultValue={nvalue
                    ?.filter((it) => it.lifePieceAccountId == record.id)?.[0]
                    ?.lineStockUseList.map((i) => ({
                      id: i.lineStockId,
                      operateNum: i.operateNum,
                    }))}
                  columns={[
                    {
                      title: '线边库',
                      dataIndex: 'stockName',
                      search: false,
                      key: 'stockName',
                      editable: false,
                    },
                    {
                      title: '供应商编号',
                      dataIndex: 'supplierNo',
                      key: 'supplierNo',
                      search: false,
                      editable: false,
                    },
                    {
                      title: '供应商名称',
                      dataIndex: 'supplierName',
                      search: false,
                      key: 'supplierName',
                      editable: false,
                    },
                    {
                      title: '可用数量',
                      dataIndex: 'usedStock',
                      search: false,
                      key: 'usedStock',
                      editable: false,
                    },
                    {
                      title: (
                        <div>
                          更换数量 <span style={{ color: 'red' }}>* </span>
                        </div>
                      ),
                      dataIndex: 'operateNum',
                      search: false,
                      key: 'operateNum',
                      valueType: 'digit',
                      fieldProps: {
                        precision: 3,
                      },
                    },
                  ]}
                  dataSource={allDatasource[record.id]}
                  extraparams={allDatasource}
                  rowSelection={{
                    getCheckboxProps: (record) => ({
                      disabled: record.isAsh == '1',
                    }),
                    columnWidth: 44,
                    preserveSelectedRowKeys: true,
                    selectedRowKeys: curvalue?.lineStockUseList
                      ? curvalue.lineStockUseList?.map?.((it) => it?.lineStockId)
                      : [],
                    onChange: async (selectedKeys, selectedRows) => {
                      //   debugger;

                      const curval = curvalue?.lineStockUseList ?? [];
                      const rowkeylist = curval?.map?.((it) => it?.lineStockId);

                      const newValue = selectedRows?.map((its) => {
                        if (rowkeylist?.includes(its?.id)) {
                          return curval?.filter((it) => it?.lineStockId == its?.id)[0];
                        } else {
                          return {
                            lineStockId: its.id,
                            operateNum: its.operateNum,
                          };
                        }
                      });

                      let nvalue = value ? [...value] : [];
                      if (value && value?.some((it) => it.lifePieceAccountId == record?.id)) {
                        nvalue = value?.map((it, i) => {
                          if (it.lifePieceAccountId == record.id) {
                            it.lineStockUseList = newValue;
                          }
                          return it;
                        });
                      } else {
                        nvalue.push({
                          lifePieceAccountId: record?.id,
                          lineStockUseList: newValue,
                        });
                      }
                      // console.log('nvalue', nvalue);
                      nvalue = nvalue.filter((it) => it.lineStockUseList.length !== 0);
                      await onChange(nvalue);
                      await setnvalue(nvalue);
                    },
                  }}
                  editable={{
                    onValuesChange: async (rower, recordList) => {
                      const curval = curvalue?.lineStockUseList ?? [];
                      const newValue = curval?.map((its) => {
                        if (its?.lineStockId == rower?.id) {
                          return {
                            lineStockId: rower.id,
                            operateNum: rower.operateNum,
                          };
                        } else {
                          return its;
                        }
                      });
                      let nvalue = value ? [...value] : [];
                      if (value && value?.some((it) => it.lifePieceAccountId == record?.id)) {
                        nvalue = value?.map((it, i) => {
                          if (it.lifePieceAccountId == record.id) {
                            it.lineStockUseList = newValue;
                          }
                          return it;
                        });
                      } else {
                        nvalue.push({
                          lifePieceAccountId: record.id,
                          lineStockUseList: newValue,
                        });
                      }
                      // console.log('nvalue', nvalue);
                      await onChange(nvalue);
                      await setnvalue(nvalue);
                    },
                  }}
                />
              </>
            );
          },
        }}
      />
    </div>
  );
}

export default Expandables;
