import React, { useEffect, useReducer, useRef } from "react";
import {
  Button,
  Drawer,
  Steps,
  Form,
  Popconfirm,
  Switch,
  Tabs,
  Tooltip,
  Row,
  Col,
  message,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import { addFields, issueFields } from "./fields";
import { doFetch } from "@/utils/doFetch";
import moment from "moment";
import { prodorderDetail } from "@/utils/detailTotalCard";
import Details from "@/components/Details";
import Coltext from "@/components/Coltext";
const { Step } = Steps,
  { TabPane } = Tabs;
const initState = {
    vs: false,
    fields: {},
    iftype: {},
    curitem: {},
    currentStep: 0,
    orderId: "",
    fieldsValue: {},
    btnLoading: false,
    tabeTep: [],
    tabKey: "",
    editType: "",
    fieldsc: {},
    visible: false,
    detail: {
      dataSource: {},
      totalCard: [],
    },
    detailsVisible: false,
    expandedRowKeys: [],
    activeTabKey: "1",
    issueData: [],
  },
  tabList = [
    {
      key: "1",
      tab: "未完成",
    },
    {
      key: "2",
      tab: "已完成",
    },
  ],
  otherBasic = {
    materieCode: "物料编号",
    materieName: "物料名称",
    materieTypeName: "物料类别",
    processLineCode: "工艺路线编号",
    processLineName: "工艺路线名称",
    factoryName: "所属工厂",
    shopName: "所属车间",
  };
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "add":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "新增生产订单",
          val: type,
        },
        fields: { ...action.fields },
      };
      break;
    case "addBom":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "新增物料BOM",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "addProcess":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: action.title,
          val: type,
          isTopRightAdd: action.isTopRightAdd,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "修改生产订单",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
        editType: action.editType,
      };
      break;
    case "editBom":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "编辑物料BOM",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "issue":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "下达",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
        issueData: action.issueData,
      };
      break;
    case "setCurrent":
      newState = {
        ...state,
        currentStep: action.currentStep,
      };
      break;
    case "changeOrderId":
      newState = {
        ...state,
        orderId: action.orderId,
      };
      break;
    case "changeValues":
      newState = {
        ...state,
        fieldsValue: { ...action.fieldsValue },
      };
      break;
    case "changeLoading":
      newState = {
        ...state,
        btnLoading: action.btnLoading,
      };
      break;
    case "changeTableTep":
      newState = {
        ...state,
        tabeTep: action.tabeTep,
      };
      break;
    case "changeFields":
      newState = {
        ...state,
        fields: { ...action.fields },
      };
      break;
    case "changeTabKey":
      newState = {
        ...state,
        tabKey: action.tabKey,
      };
      break;
    case "changeactiveTabKey":
      newState = {
        ...state,
        activeTabKey: action.activeTabKey,
      };
      break;
    case "changeEditType":
      newState = {
        ...state,
        editType: action.editType,
      };
      break;
    case "closeBom":
      newState = {
        ...state,
        fieldsc: {},
        visible: false,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: action.totalCard,
        },
        detailsVisible: true,
      };
      break;
    case "changeExpand":
      newState = {
        ...state,
        expandedRowKeys: action.expandedRowKeys,
      };
      break;
    case "changeissueData":
      newState = {
        ...state,
        issueData: action.issueData,
      };
      break;
    case "changeFieldsc":
      newState = {
        ...state,
        fieldsc: action.fieldsc,
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        currentStep: 0,
        orderId: "",
        btnLoading: false,
        tabeTep: [],
        tabKey: "",
        fieldsValue: {},
        editType: "",
        fieldsc: {},
        visible: false,
        detailsVisible: false,
        detail: {
          dataSource: {},
          totalCard: [],
        },
        expandedRowKeys: [],
        issueData: [],
      };
      break;
  }

  return newState;
}
const Prodorder = (props) => {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm(),
    actionRefs = useRef(),
    actionRefc = useRef(),
    [issueFormRef] = Form.useForm();
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  function reloads() {
    actionRefc?.current?.reload();
    actionRefs?.current?.reload();
    dispatch({ type: "closeBom" });
  }
  let extrarender = [
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        type="primary"
        onClick={() => {
          for (let i in addFields) {
            addFields[i].value = null;
            addFields[i].disabled = false;
          }
          dispatch({ type: "add", fields: addFields });
        }}
      >
        新增
      </Button>,
    ],
    extrarenders = [
      <Button
        disabled={!getPrem("sysDepartment_save", "ifs")}
        type="primary"
        onClick={() => {
          if (currentStep == 1) {
            addBomFn({ materieId: fieldsValue.materieId }, null);
          } else if (currentStep == 2) {
            addProcessFn(null, true, "新增步骤和工序");
          }
        }}
      >
        新增
      </Button>,
    ];
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          reloads();
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    {
      vs,
      fields,
      iftype,
      curitem,
      currentStep,
      orderId,
      fieldsValue,
      btnLoading,
      tabeTep,
      tabKey,
      editType,
      visible,
      fieldsc,
      detail,
      detailsVisible,
      expandedRowKeys,
      activeTabKey,
      issueData,
    } = state,
    columns = [
      {
        title: "生产订单编号",
        dataIndex: "productionOrderNo",
        key: "productionOrderNo",
        render: (_, row) => {
          return (
            <Tooltip title={row.productionOrderNo}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-production/umProductionOrder/queryById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      let bottom = [
                          {
                            cardTitle: "物料BOM信息",
                            itemData: [
                              {
                                key: "materieBomTreeList",
                                rowKey: "key",
                                type: "table",
                                columns: [
                                  {
                                    title: "原料标识",
                                    dataIndex: "isRawMaterial",
                                    key: "isRawMaterial",
                                    search: false,
                                    render: (_, row) => {
                                      return (
                                        <div>
                                          {row.isRawMaterial == 1 ? "是" : "否"}
                                        </div>
                                      );
                                    },
                                  },
                                  {
                                    title: "物料编号",
                                    dataIndex: "title",
                                    key: "title",
                                    search: false,
                                  },
                                  {
                                    title: "物料名称",
                                    dataIndex: "materieName",
                                    key: "materieName",
                                    search: false,
                                  },
                                  {
                                    title: "生产单位",
                                    dataIndex: "productionUnitName",
                                    key: "productionUnitName",
                                    search: false,
                                  },
                                  {
                                    title: "物料类别",
                                    dataIndex: "materieTypeName",
                                    key: "materieTypeName",
                                    search: false,
                                  },
                                  {
                                    title: "台份量",
                                    dataIndex: "numberUnits",
                                    key: "numberUnits",
                                    search: false,
                                  },
                                  {
                                    title: "预投量",
                                    dataIndex: "planQuantity",
                                    key: "planQuantity",
                                    search: false,
                                  },
                                  {
                                    title: "产出工序",
                                    dataIndex: "workingProduceName",
                                    key: "workingProduceName",
                                    search: false,
                                  },
                                  {
                                    title: "投料工序",
                                    dataIndex: "workingFeedingName",
                                    key: "workingFeedingName",
                                    search: false,
                                  },
                                ],
                                col: { span: 24 },
                                expandable: {
                                  defaultExpandedRowKeys:
                                    dataSource.materieBomTreeList?.length > 0
                                      ? [dataSource.materieBomTreeList[0]?.key]
                                      : [],
                                },
                              },
                            ],
                          },
                          {
                            cardTitle: "工艺路线信息",
                            itemData: [
                              {
                                key: "lineList",
                                type: "table",
                                columns: [
                                  {
                                    title: "工艺路线编号",
                                    dataIndex: "processLineCode",
                                    key: "processLineCode",
                                    search: false,
                                  },
                                  {
                                    title: "工艺路线名称",
                                    dataIndex: "processLineName",
                                    key: "processLineName",
                                  },
                                  {
                                    title: "物料编号",
                                    dataIndex: "materieCode",
                                    key: "materieCode",
                                  },
                                  {
                                    title: "物料名称",
                                    dataIndex: "materieName",
                                    key: "materieName",
                                  },
                                  {
                                    title: "所属工厂",
                                    dataIndex: "factoryName",
                                    key: "factoryName",
                                  },
                                  {
                                    title: "所属车间",
                                    dataIndex: "shopName",
                                    key: "shopName",
                                  },
                                  {
                                    title: "工序信息",
                                    dataIndex: "stepProcedure",
                                    key: "stepProcedure",
                                  },
                                ],
                                col: { span: 24 },
                              },
                            ],
                          },
                        ],
                        totalCard = [...prodorderDetail, ...bottom];
                      dispatch({ type: "see", dataSource, totalCard });
                    }
                  });
                }}
              >
                {row.productionOrderNo}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "产出物料编号",
        dataIndex: "materieCode",
        key: "materieCode",
      },
      {
        title: "产出物料名称",
        dataIndex: "materieName",
        key: "materieName",
      },
      {
        title: "产出物料单位",
        dataIndex: "productionUnitName",
        key: "productionUnitName",
        search: false,
      },
      {
        title: "订单数量",
        dataIndex: "orderNum",
        key: "orderNum",
        search: false,
      },
      {
        title: "计划开工时间",
        dataIndex: "planStartDate",
        key: "planStartDate",
        search: false,
      },
      {
        title: "计划完工时间",
        dataIndex: "planEndDate",
        key: "planEndDate",
        search: false,
      },
      {
        title: "生产订单状态",
        dataIndex: "statusName",
        key: "statusName",
        search: false,
      },
      {
        title: "已排产数量",
        dataIndex: "scheduledProductionNum",
        key: "scheduledProductionNum",
        search: false,
      },
      {
        title: "完成数量",
        dataIndex: "finishNum",
        key: "finishNum",
        search: false,
      },
      {
        title: "销售订单号",
        dataIndex: "saleOrderNo",
        key: "saleOrderNo",
      },
      {
        title: "行号",
        dataIndex: "lineNo",
        key: "lineNo",
        search: false,
      },
      {
        title: "客户名称",
        dataIndex: "customerName",
        key: "customerName",
      },
      {
        title: "规格",
        dataIndex: "specs",
        key: "specs",
        search: false,
      },
      {
        title: "颜色",
        dataIndex: "color",
        key: "color",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnsc = [
      {
        title: "物料编号",
        dataIndex: "title",
        key: "title",
        search: false,
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
        search: false,
      },
      {
        title: "物料类别",
        dataIndex: "materieTypeName",
        key: "materieTypeName",
        search: false,
      },
      {
        title: "台份量",
        dataIndex: "numberUnits",
        key: "numberUnits",
        search: false,
      },
      {
        title: "预投量（系统计算）",
        dataIndex: "planQuantity",
        key: "planQuantity",
        search: false,
      },
      {
        title: "产出工序",
        dataIndex: "workingProduceName",
        key: "workingProduceName",
        search: false,
      },
      {
        title: "投料工序",
        dataIndex: "workingFeedingName",
        key: "workingFeedingName",
        search: false,
      },
      {
        title: "作为原料",
        dataIndex: "material",
        key: "material",
        valueType: "switch",
        width: 85,
        render: (text, row, _, action) => {
          return row.parentKey != "0" ? (
            <Popconfirm
              title={`${row.isRawMaterial == 1 ? "是否关闭?" : "是否开启?"}`}
              onConfirm={() => {
                doFetch({
                  url: "/ngic-production/omOrderMaterieBomTmp/updateIsRawMaterial",
                  params: {
                    id: row.key,
                    isRawMaterial: row.isRawMaterial == 1 ? 0 : 1,
                  },
                }).then((res) => {
                  if (res.code == "0000") {
                    actionRefs?.current?.reload();
                  }
                });
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="取消"
              disabled={!getPrem("equipmentSupplier_updatestatus", "ifs")}
            >
              <Switch
                checked={row.isRawMaterial == 1 ? true : false}
                checkedChildren="开启"
                unCheckedChildren="关闭"
                defaultChecked={false}
              />
            </Popconfirm>
          ) : (
            <></>
          );
        },
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraActions(text, row, _, action),
      },
    ],
    columnss = [
      {
        title: "步骤号",
        dataIndex: "stepSort",
        key: "stepSort",
        search: false,
      },
      {
        title: "工序编号",
        dataIndex: "title",
        key: "title",
        search: false,
      },
      {
        title: "工序名称",
        dataIndex: "workingProcedureName",
        key: "workingProcedureName",
        search: false,
      },
      {
        title: "工序类型",
        dataIndex: "workingProcedureTypeName",
        key: "workingProcedureTypeName",
        search: false,
      },
      {
        title: "采集方式",
        dataIndex: "collectionModeName",
        key: "collectionModeName",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraActions(text, row, _, action),
      },
    ],
    steps = [
      {
        title: "基础信息",
        content: (
          <InitForm
            fields={fields}
            onChange={(changedValues, allValues) => {}}
            formRef={formRef}
            actions={(form, submitBtn) => {
              return null;
            }}
            rowCol={0}
          ></InitForm>
        ),
      },
      {
        title: "物料BOM",
        content: (
          <AutoTable
            columns={columnsc}
            path="/ngic-production/omOrderMaterieBomTmp/queryTreeList"
            actionRef={actionRefs}
            extraparams={{ productionOrderId: orderId }}
            pagination="false"
            rowKey={"key"}
            expandable={{
              expandedRowKeys: expandedRowKeys ?? [],
              rowExpandable: true,
              onExpand: (expanded, record) => {
                if (expanded) {
                  dispatch({
                    type: "changeExpand",
                    expandedRowKeys: [...expandedRowKeys, record.key],
                  });
                } else {
                  let newKeys = expandedRowKeys.filter(
                    (it) => it != record.key
                  );
                  dispatch({
                    type: "changeExpand",
                    expandedRowKeys: [...newKeys],
                  });
                }
              },
            }}
          ></AutoTable>
        ),
      },
      {
        title: "工艺路线",
        content: (
          <Tabs
            activeKey={tabKey}
            onChange={(key) => {
              dispatch({ type: "changeTabKey", tabKey: key });
            }}
          >
            {tabeTep.map((it, i) => (
              <TabPane tab={it.processLineName} key={it.id}>
                <div style={{ margin: "20px 0" }}>
                  <Row gutter={[16, 10]}>
                    {Object.keys(otherBasic).map((item) => {
                      return (
                        <Coltext
                          label={otherBasic[item]}
                          value={it[item]}
                          key={item}
                        />
                      );
                    })}
                  </Row>
                </div>
                <AutoTable
                  pageextra={extrarenders}
                  columns={columnss}
                  path="/ngic-production/omOrderProcessLineStepTmp/queryTreeList"
                  actionRef={actionRefc}
                  extraparams={{ id: it.id }}
                  pagination="false"
                  rowKey={"key"}
                ></AutoTable>
              </TabPane>
            ))}
          </Tabs>
        ),
      },
    ];
  function extraAction(text, record, _, action) {
    // status  1 未下达  2已下达  3 已撤回  4生产中  5已完成
    let ifs = record.status == 1 || record.status == 3,
      ifsc = record.status == 2;
    return [
      ifs &&
        getPrem("sysDepartment_save", action, "修改", () => {
          for (let i in addFields) {
            addFields[i].value = record[i];
          }
          dispatch({
            type: "edit",
            fields: addFields,
            curitem: record,
            editType: "mastEdit",
          });
          dispatch({ type: "changeOrderId", orderId: record?.id });
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "下达", () => {
          doFetch({
            url: "/ngic-production/omShopPlanTmp/queryByOrderId",
            params: { id: record.id },
          }).then((res) => {
            if (res.code == "0000") {
              let data = res?.data?.dataList ?? [];
              for (let i in issueFields) {
                issueFields[i].value = data;
                issueFields[i].columns[11] = {
                  title: "操作",
                  dataIndex: "option_dataindex",
                  key: "option_dataindex",
                  valueType: "option",
                  search: false,
                  editable: false,
                  render: (text, row, index, action) => {
                    return [
                      index != 0 && (
                        <a
                          key="aesc"
                          onClick={() => {
                            asce(index, issueFields[i].value);
                          }}
                        >
                          升序
                        </a>
                      ),
                      index != data.length - 1 && (
                        <a
                          key="desc"
                          onClick={() => {
                            desc(index, issueFields[i].value);
                          }}
                        >
                          降序
                        </a>
                      ),
                    ];
                  },
                };
              }
              dispatch({
                type: "issue",
                fieldsc: issueFields,
                curitem: record,
                issueData: data,
              });
            }
          });
        }),
      ifsc &&
        getPrem("sysDepartment_deleteById", action, "撤回", null, {
          title: "确认撤回该生产订单？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umProductionOrder/recall",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title: "确认删除该生产订单？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umProductionOrder/deleteById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
    ];
  }
  function extraActions(text, record, index, action) {
    return [
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "升序", () => {
          run({
            url: "/ngic-production/omOrderProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 1 },
          });
        }),
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "降序", () => {
          run({
            url: "/ngic-production/omOrderProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 2 },
          });
        }),
      ((currentStep == 1 && record.materieType != 1) ||
        record.parentKey == "0") &&
        getPrem("sysDepartment_save", action, "新增", () => {
          if (currentStep == 1) {
            addBomFn({ id: record.key }, record);
          } else if (currentStep == 2) {
            addProcessFn(record, false, "新增工序");
          }
        }),
      currentStep == 1 &&
        record.parentKey != "0" &&
        getPrem("sysDepartment_save", action, "修改", () => {
          if (currentStep == 1) {
            let fieldsc = {
              materieCode: {
                value: null,
                type: "input",
                title: "物料编号",
                name: ["materieCode"],
                required: false,
                disabled: true,
              },
              materieName: {
                value: null,
                type: "input",
                title: "物料名称",
                name: ["materieName"],
                required: false,
                disabled: true,
              },
              materieTypeName: {
                value: null,
                type: "input",
                title: "物料类别",
                name: ["materieTypeName"],
                required: false,
                disabled: true,
              },
              numberUnits: {
                value: null,
                type: "inputnumber",
                title: "台份量",
                name: ["numberUnits"],
                required: true,
              },
              workingProduceId: {
                value: null,
                type: "select",
                title: "产出工序",
                name: ["workingProduceId"],
                required: true,
              },
              workingFeedingId: {
                value: null,
                type: "select",
                title: "投料工序",
                name: ["workingFeedingId"],
                required: true,
              },
            };

            let all = async () => {
              let mark = await doFetch({
                  url: "/ngic-base-business/bmSpecialSet/queryByMark",
                  params: { mark: "materiel_bom" },
                }),
                tem = await doFetch({
                  url: "/ngic-production/omOrderMaterieBomTmp/queryUpdateMaterie",
                  params: { id: record.key },
                });
              return {
                markKey: mark?.data?.value,
                temData: tem?.data?.data,
              };
            };
            all().then((res) => {
              const { markKey, temData } = res;
              for (let i in fieldsc) {
                fieldsc[i].value = record[i];
                if (i == "workingProduceId") {
                  fieldsc[i].options = temData?.workingProduceList ?? [];
                  if (record.materieType == 1 || markKey == 2) {
                    fieldsc["workingProduceId"].hides = true;
                  } else {
                    fieldsc["workingProduceId"].hides = false;
                  }
                }
                if (i == "workingFeedingId") {
                  fieldsc[i].options = temData?.workingFeedingList ?? [];
                  if (markKey == 2) {
                    fieldsc["workingFeedingId"].hides = true;
                  } else {
                    fieldsc["workingFeedingId"].hides = false;
                  }
                }
                if (i == "materieCode") {
                  fieldsc[i].value = record.title;
                }
              }
              dispatch({ type: "editBom", fieldsc, curitem: record });
            });
          }
        }),
      ((currentStep == 1 && record.parentKey != "0") || currentStep == 2) &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title:
            currentStep == 1
              ? "确认删除该物料BOM？"
              : record.parentKey == 0
              ? "确认删除该步骤？"
              : "确认删除该工序？",
          onConfirm: () => {
            run({
              url:
                currentStep == 1
                  ? "/ngic-production/omOrderMaterieBomTmp/deleteById"
                  : record.parentKey == 0
                  ? "/ngic-production/omOrderProcessLineStepTmp/deleteById"
                  : "/ngic-production/omOrderProcessLineStepProcedureTmp/deleteById",
              params: { id: record.key },
            });
          },
        }),
    ];
  }
  const next = () => {
    let newStep = currentStep + 1;
    if (currentStep == 0) {
      let editId =
        editType == "mastEdit"
          ? { productionOrderId: orderId }
          : { id: orderId };
      formRef.validateFields().then((values) => {
        let newValues = JSON.parse(JSON.stringify(values));
        newValues.planEndDate = moment(newValues.planEndDate).format(
          "YYYY-MM-DD"
        );
        newValues.planStartDate = moment(newValues.planStartDate).format(
          "YYYY-MM-DD"
        );
        dispatch({ type: "changeLoading", btnLoading: true });
        doFetch({
          url: "/ngic-production/omProductionOrderTmp/save",
          params: { ...newValues, ...editId },
        }).then((res) => {
          if (res.code == "0000") {
            let dataId = res?.data?.data ?? "";
            dispatch({ type: "changeOrderId", orderId: dataId });
            dispatch({ type: "changeValues", fieldsValue: { ...newValues } });
            dispatch({ type: "setCurrent", currentStep: newStep });
            dispatch({ type: "changeLoading", btnLoading: false });
            getExpend(dataId);
          }
        });
      });
    }
    if (currentStep == 1) {
      doFetch({
        url: "/ngic-production/omOrderMaterieBomTmp/check",
        params: { productionOrderId: orderId },
      }).then((res) => {
        if (res.code == "0000") {
          doFetch({
            url: "/ngic-production/omOrderProcessLineTmp/queryListByOrderId",
            params: { productionOrderId: orderId },
          }).then((res) => {
            if (res.code == "0000") {
              let data = res?.data?.dataList ?? [];
              dispatch({ type: "changeTableTep", tabeTep: [...data] });
              dispatch({ type: "changeTabKey", tabKey: data[0]?.id ?? "" });
            }
          });
          dispatch({ type: "setCurrent", currentStep: newStep });
        }
      });
    }
  };
  const prev = () => {
    let newStep = currentStep - 1;
    if (newStep == 0) {
      for (let i in addFields) {
        addFields[i].value = fieldsValue[i];
      }
      dispatch({ type: "changeFields", fields: addFields });
      dispatch({ type: "changeEditType", editType: "prevEdit" });
    }
    if (newStep == 1) {
      getExpend(orderId);
    }
    dispatch({ type: "setCurrent", currentStep: newStep });
  };
  function addBomFn(idparams, record) {
    let all = async () => {
      let mark = await doFetch({
        url: "/ngic-base-business/bmSpecialSet/queryByMark",
        params: { mark: "materiel_bom" },
      });
      return {
        markKey: mark?.data?.value,
      };
    };
    all().then((res) => {
      const { markKey } = res;
      let fieldsc = {
        list: {
          value: [],
          title: "物料",
          type: "checktable",
          col: { span: 24 },
          name: ["list"],
          required: false,
          editable: true,
          columns: [
            {
              title: "物料编号",
              dataIndex: "materieCode",
              key: "materieCode",
            },
            {
              title: "物料名称",
              dataIndex: "materieName",
              key: "materieName",
            },
            {
              title: "物料类别",
              dataIndex: "materieTypeName",
              key: "materieTypeName",
              search: false,
            },
            {
              title: "台份量",
              dataIndex: "numberUnits",
              key: "numberUnits",
              width: 110,
              search: false,
              selectedRender: "InputNumber",
            },
            {
              title: "产出工序",
              dataIndex: "workingProduceId",
              key: "workingProduceId",
              width: 150,
              search: false,
              selectedRender: markKey == 2 ? "" : "Select",
              optionsFields: "workingProduceList",
              renderNull: [
                {
                  name: "materieType",
                  equalvalue: [1],
                },
              ],
            },
            {
              title: "投料工序",
              dataIndex: "workingFeedingId",
              key: "workingFeedingId",
              width: 150,
              search: false,
              selectedRender: markKey == 2 ? "" : "Select",
              optionsFields: "workingFeedingList",
            },
          ],
          path: "/ngic-production/omOrderMaterieBomTmp/queryAddMateriePage",
          extraparams: idparams,
          rowKey: "id",
          rowName: "materieName",
        },
      };
      dispatch({ type: "addBom", fieldsc, curitem: record, markKey });
    });
  }
  function addProcessFn(record, isTopRightAdd, title) {
    let fieldsc = {
      procedureList: {
        value: [],
        title: "工序",
        type: "checktable",
        col: { span: 24 },
        name: ["procedureList"],
        required: false,
        editable: false,
        columns: [
          {
            title: "工序编号",
            dataIndex: "workingProcedureCode",
            key: "workingProcedureCode",
          },
          {
            title: "工序名称",
            dataIndex: "workingProcedureName",
            key: "workingProcedureName",
          },
          {
            title: "工序类型",
            dataIndex: "workingProcedureTypeName",
            key: "workingProcedureTypeName",
            search: false,
          },
          {
            title: "采集方式",
            dataIndex: "collectionModeName",
            key: "collectionModeName",
            search: false,
          },
        ],
        path: "/ngic-production/omOrderProcessLineStepProcedureTmp/queryAddProcedurePage",
        extraparams: { id: tabKey },
        rowKey: "id",
        rowName: "workingProcedureName",
      },
    };
    dispatch({
      type: "addProcess",
      fieldsc,
      curitem: record,
      isTopRightAdd: isTopRightAdd,
      title,
    });
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let params, url;

    if (iftype.val != "issue") {
      if (iftype.val == "addBom") {
        newfields.list = newfields.list.map((it) => {
          return {
            materieId: it.id,
            numberUnits: it.numberUnits,
            workingProduceId: it.workingProduceId,
            workingFeedingId: it.workingFeedingId,
          };
        });
        params = {
          ...newfields,
          productionOrderId: orderId,
          parentId: curitem.key,
        };
        url = "/ngic-production/omOrderMaterieBomTmp/save";
      } else if (iftype.val == "editBom") {
        params = {
          numberUnits: newfields.numberUnits,
          workingProduceId: newfields.workingProduceId,
          workingFeedingId: newfields.workingFeedingId,
          id: curitem.key,
        };
        url = "/ngic-production/omOrderMaterieBomTmp/save";
      } else if (iftype.val == "addProcess") {
        newfields.procedureList = newfields.procedureList.map((it) => {
          return {
            workingProcedureId: it,
          };
        });
        url = "/ngic-production/omOrderProcessLineStepTmp/add";
        params = {
          ...newfields,
          productionOrderId: orderId,
          processLineId: tabKey,
          id: iftype.isTopRightAdd ? "" : curitem.key,
        };
      }
      run({ url, params });
    } else {
      url = "/ngic-production/omShopPlanTmp/submitRelease";
      let newList = newfields.list.map((it) => {
        return {
          id: it.id,
          planStartDate: it.planStartDate,
          planEndDate: it.planEndDate,
        };
      });
      doFetch({ url, params: newList }).then((res) => {
        if (res.code == "0000") {
          reload();
          dispatch({ type: "closeBom" });
        }
      });
    }
  };
  const asce = (currentIndex, data) => {
      let firstData = data.slice(0, currentIndex - 1) ?? [],
        lastData = data.slice(currentIndex + 1, data.length) ?? [],
        currentData = data.slice(currentIndex, currentIndex + 1) ?? [],
        prveData = data.slice(currentIndex - 1, currentIndex) ?? [],
        newData = [...firstData, ...currentData, ...prveData, ...lastData];
      for (let i in issueFields) {
        issueFields[i].value = [...newData];
      }
      issueFormRef.setFieldsValue({ list: newData });
      dispatch({ type: "changeFieldsc", fieldsc: issueFields });
    },
    desc = (currentIndex, data) => {
      let firstData = data.slice(0, currentIndex) ?? [],
        lastData = data.slice(currentIndex + 2, data.length) ?? [],
        currentData = data.slice(currentIndex, currentIndex + 1) ?? [],
        nextData = data.slice(currentIndex + 1, currentIndex + 2) ?? [],
        newData = [...firstData, ...nextData, ...currentData, ...lastData];
      for (let i in issueFields) {
        issueFields[i].value = newData;
      }
      issueFormRef.setFieldsValue({ list: newData });
      dispatch({ type: "changeFieldsc", fieldsc: issueFields });
    };
  function getExpend(dataId) {
    doFetch({
      url: "/ngic-production/omOrderMaterieBomTmp/queryTreeList",
      params: { productionOrderId: dataId },
    }).then((res) => {
      if (res.code == "0000") {
        let dataTree = res?.data?.dataList ?? [];
        dispatch({
          type: "changeExpand",
          expandedRowKeys:
            dataTree?.length > 0
              ? dataTree[0].parentKey == "0"
                ? [dataTree[0].key]
                : []
              : [],
        });
      }
    });
  }

  return (
    <div>
      <AutoTable
        pagetitle={props.route.name}
        pageextra={activeTabKey == "1" ? extrarender : null}
        columns={
          activeTabKey == "1"
            ? columns
            : columns.filter((it) => it.valueType != "option")
        }
        path={
          activeTabKey == "1"
            ? "/ngic-production/umProductionOrder/queryNotFinishList"
            : "/ngic-production/umProductionOrder/queryFinishList"
        }
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        tabList={tabList}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          dispatch({ type: "changeactiveTabKey", activeTabKey: key });
        }}
      ></AutoTable>

      <Drawer
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <>
          <div style={{ marginBottom: 15 }}>
            <Steps current={currentStep}>
              {steps.map((item) => (
                <Step key={item.title} title={item.title} />
              ))}
            </Steps>
          </div>
          <div className="steps-content">{steps[currentStep].content}</div>
          <div
            style={{
              display: "flex",
              width: "100%",
              justifyContent: "flex-end",
              marginTop: 15,
            }}
          >
            {currentStep > 0 && (
              <Button style={{ margin: "0 15px" }} onClick={() => prev()}>
                上一步
              </Button>
            )}
            {currentStep < steps.length - 1 && (
              <Button
                loading={btnLoading}
                type="primary"
                onClick={() => next()}
              >
                下一步
              </Button>
            )}
            {currentStep === steps.length - 1 && (
              <Button
                loading={btnLoading}
                type="primary"
                onClick={() => {
                  dispatch({ type: "changeLoading", btnLoading: true });
                  doFetch({
                    url: "/ngic-production/omProductionOrderTmp/submit",
                    params: { id: orderId },
                  }).then((res) => {
                    if (res.code == "0000") {
                      reload();
                      dispatch({ type: "close" });
                      dispatch({ type: "changeLoading", btnLoading: false });
                    }
                  });
                }}
              >
                提交
              </Button>
            )}
          </div>
        </>
      </Drawer>
      <Drawer
        title={iftype.title}
        visible={visible}
        onClose={() => dispatch({ type: "closeBom" })}
        footer={false}
        destroyOnClose={true}
        width={iftype.val == "issue" ? "100%" : 900}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <InitForm
          fields={fieldsc}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          onChange={(changedValues, allValues) => {}}
          submitting={loading || !visible}
          formRef={issueFormRef}
        ></InitForm>
      </Drawer>
      <Details
        title="生产订单详情"
        visible={detailsVisible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        {...detail}
      ></Details>
    </div>
  );
};
export default Prodorder;
