import React, { useEffect, useReducer, useRef } from "react";
import { Button, Form, Checkbox, Table } from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import { sortFields } from "./fields";
import moment from "moment";
import { doFetch } from "@/utils/doFetch";
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from "react-sortable-hoc";
import { MenuOutlined } from "@ant-design/icons";
import { arrayMoveImmutable } from "array-move";
const CheckboxGroup = Checkbox.Group;
const initState = {
  topfields: {},
  searchLoading: false,
  topTableData: [],
  bottomTableData: [],
  paramsForm: {},
};
const DragHandle = SortableHandle(() => (
  <MenuOutlined style={{ cursor: "grab", color: "#999" }} />
));
const SortableItem = SortableElement((props) => <tr {...props} />);
const SortableBody = SortableContainer((props) => <tbody {...props} />);
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "changetopfields":
      newState = {
        ...state,
        topfields: action.topfields,
      };
      break;
    case "changeSearchLoading":
      newState = {
        ...state,
        searchLoading: action.searchLoading,
      };
      break;
    case "changeTop":
      newState = {
        ...state,
        topTableData: action.topTableData,
      };
      break;
    case "changeBottom":
      newState = {
        ...state,
        bottomTableData: action.bottomTableData,
      };
      break;
    case "changeParams":
      newState = {
        ...state,
        paramsForm: action.paramsForm,
      };
      break;
    case "close":
      newState = {
        topfields: {},
        searchLoading: false,
        topTableData: [],
        bottomTableData: [],
      };
      break;
  }

  return newState;
}

const Setsort = ({ reset, schedulingVisible }) => {
  const [state, dispatch] = useReducer(reducer, initState),
    { topfields, searchLoading, topTableData, bottomTableData, paramsForm } =
      state,
    [leftFormRef] = Form.useForm();
  useEffect(() => {
    dispatch({ type: "changetopfields", topfields: { ...sortFields } });
  }, []);
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          getBottomData(paramsForm);
        }
      },
    }),
    columns = [
      {
        title: "排序",
        dataIndex: "sort",
        valueType: "option",
        width: 80,
        className: "drag-visible",
        render: () => <DragHandle />,
      },
      {
        title: "派工单编号",
        dataIndex: "jobOrderNo",
        key: "jobOrderNo",
        search: false,
      },
      {
        title: "物料编号",
        dataIndex: "materieCode",
        key: "materieCode",
        search: false,
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
        search: false,
      },
      {
        title: "生产单位",
        dataIndex: "productionUnitName",
        key: "productionUnitName",
        search: false,
      },
      {
        title: "排产数量",
        dataIndex: "scheduledProductionNum",
        key: "scheduledProductionNum",
        search: false,
      },
      {
        title: "车间计划编号",
        dataIndex: "shopPlanNo",
        key: "shopPlanNo",
        render: (_, row) => {
          return (
            <div className="table-cell">
              {row.shopPlanNo
                ? `${row.shopPlanNo}（${row.planStartDate}~${row.planEndDate}）`
                : ""}
            </div>
          );
        },
        search: false,
      },
      {
        title: "生产订单编号",
        dataIndex: "productionOrderNo",
        key: "productionOrderNo",
        render: (_, row) => {
          return (
            <div className="table-cell">
              {row.productionOrderNo
                ? `${row.productionOrderNo}（${row.orderStartDate}~${row.orderEndDate}`
                : ""}
            </div>
          );
        },
        search: false,
      },
      {
        title: "状态",
        dataIndex: "statusName",
        key: "statusName",
        search: false,
      },
      {
        title: "排序号",
        dataIndex: "sortNo",
        key: "sortNo",
        search: false,
      },
    ];
  const onSortEnd = ({ oldIndex, newIndex }) => {
      if (oldIndex !== newIndex) {
        const newData = arrayMoveImmutable(
          [].concat(bottomTableData),
          oldIndex,
          newIndex
        ).filter((el) => !!el);
        const params = newData.map((it) => {
          return {
            id: it.id,
            sortNo: it.sortNo,
          };
        });
        run({ url: "/ngic-production/umJobOrder/upDownList", params });
        // dispatch({ type: "changeBottom", bottomTableData: newData })
      }
    },
    DraggableContainer = (props) => (
      <SortableBody
        useDragHandle
        disableAutoscroll
        helperClass="row-dragging"
        onSortEnd={onSortEnd}
        {...props}
      />
    ),
    DraggableBodyRow = ({ className, style, ...restProps }) => {
      const index = bottomTableData.findIndex(
        (x) => x.id === restProps["data-row-key"]
      );
      return <SortableItem index={index} {...restProps} />;
    };
  function getTopData(newFields) {
    doFetch({
      url: "/ngic-production/umJobOrder/queryProductionLineSortFinishedList",
      params: { ...newFields },
    }).then((res) => {
      if (res.code == "0000") {
        let data = res?.data?.dataList ?? [];
        dispatch({ type: "changeTop", topTableData: data });
      }
    });
  }
  function getBottomData(newFields) {
    doFetch({
      url: "/ngic-production/umJobOrder/queryProductionLineSortList",
      params: { ...newFields },
    }).then((res) => {
      if (res.code == "0000") {
        let data = res?.data?.dataList ?? [];
        dispatch({ type: "changeBottom", bottomTableData: data });
      }
    });
  }
  return (
    <div>
      <div>
        <InitForm
          fields={topfields}
          submitData={(values, fn) => {}}
          onChange={(changedValues, allValues) => {}}
          actions={(form, submitBtn) => {
            return (
              <Button
                loading={searchLoading}
                style={{ marginLeft: 12 }}
                type="primary"
                onClick={() => {
                  form
                    .validateFields()
                    .then((values) => {
                      dispatch({
                        type: "changeSearchLoading",
                        searchLoading: true,
                      });
                      let newFields = JSON.parse(JSON.stringify(values));
                      newFields.productionDate = moment(
                        newFields.productionDate
                      ).format("YYYY-MM-DD");
                      dispatch({ type: "changeParams", paramsForm: newFields });
                      getTopData(newFields);
                      getBottomData(newFields);
                      dispatch({
                        type: "changeSearchLoading",
                        searchLoading: false,
                      });
                    })
                    .catch((error) => {});
                }}
              >
                查询
              </Button>
            );
          }}
          formRef={leftFormRef}
        ></InitForm>
      </div>
      <div style={{ marginTop: 15 }}>
        <div style={{ marginBottom: 10, fontSize: 16 }}>产线排产：</div>
        <Table
          columns={columns.filter((it) => it.valueType != "option")}
          dataSource={topTableData}
          rowKey="id"
          pagination={false}
        ></Table>
      </div>
      <div style={{ marginTop: 15 }}>
        <div style={{ marginBottom: 10, fontSize: 16 }}>产线排产排序：</div>
        {!loading && (
          <Table
            columns={columns}
            dataSource={bottomTableData}
            pagination={false}
            rowKey="id"
            components={{
              body: {
                wrapper: DraggableContainer,
                row: DraggableBodyRow,
              },
            }}
          ></Table>
        )}
      </div>
    </div>
  );
};

export default Setsort;
