import React, { useEffect, useReducer, useRef } from "react";
import {
  Button,
  Drawer,
  Steps,
  Form,
  Popconfirm,
  Switch,
  Tabs,
  Card,
  Row,
  Col,
  Tooltip,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import { addFields } from "./fields";
import { doFetch } from "@/utils/doFetch";
import moment from "moment";
import { shopplanDetail } from "@/utils/detailTotalCard";
import Coltext from "@/components/Coltext";
import Details from "@/components/Details";
import styles from "./index.less";
const { Step } = Steps,
  { TabPane } = Tabs,
  otherBasic = {
    processLineCode: "工艺路线编号",
    processLineName: "工艺路线名称",
    factoryName: "所属工厂",
    shopName: "所属车间",
  },
  tabList = [
    {
      key: "1",
      tab: "未完成",
    },
    {
      key: "2",
      tab: "已完成",
    },
  ];
const initState = {
  vs: false,
  fields: {},
  iftype: {},
  curitem: {},
  currentStep: 0,
  orderId: "",
  fieldsValue: {},
  btnLoading: false,
  tabeTep: [],
  editType: "",
  fieldsc: {},
  visible: false,
  expandedRowKeys: [],
  tabKey: "",
  detail: {
    dataSource: {},
    totalCard: [],
  },
  detailsVisible: false,
  detailStepData: {},
  activeTabKey: "1",
};
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 "editIssue":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "修改车间计划",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      break;
    case "editBom":
      newState = {
        ...state,
        visible: true,
        iftype: {
          title: "编辑物料BOM",
          val: type,
        },
        fieldsc: { ...action.fieldsc },
        curitem: action.curitem,
      };
      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 "changeactiveTabKey":
      newState = {
        ...state,
        activeTabKey: action.activeTabKey,
      };
      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 "changeEditType":
      newState = {
        ...state,
        editType: action.editType,
      };
      break;
    case "closeBom":
      newState = {
        ...state,
        fieldsc: {},
        visible: false,
      };
      break;
    case "changeExpand":
      newState = {
        ...state,
        expandedRowKeys: action.expandedRowKeys,
      };
      break;
    case "changeTabKey":
      newState = {
        ...state,
        tabKey: action.tabKey,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: action.totalCard,
        },
        detailsVisible: true,
        detailStepData: action.detailStepData,
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        currentStep: 0,
        orderId: "",
        btnLoading: false,
        tabeTep: [],
        fieldsValue: {},
        editType: "",
        fieldsc: {},
        visible: false,
        expandedRowKeys: [],
        tabKey: "",
        detailsVisible: false,
        detail: {
          dataSource: {},
          totalCard: [],
        },
        detailStepData: {},
      };
      break;
  }

  return newState;
}
const Shopplan = (props) => {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm(),
    actionRefs = useRef(),
    actionRefc = useRef();
  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,
      editType,
      visible,
      fieldsc,
      expandedRowKeys,
      tabKey,
      detail,
      detailsVisible,
      detailStepData,
      activeTabKey,
    } = state,
    columns = [
      {
        title: "车间计划编号",
        dataIndex: "shopPlanNo",
        key: "shopPlanNo",
        render: (_, row) => {
          return (
            <Tooltip title={row.shopPlanNo}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-production/umShopPlan/queryDetailById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {};
                      let bottom = [
                          {
                            cardTitle: "物料BOM信息",
                            itemData: [
                              {
                                key: "umShopPlanMaterieBomList",
                                rowKey: "key",
                                type: "table",
                                columns: [
                                  {
                                    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.umShopPlanMaterieBomList
                                      ?.length > 0
                                      ? [
                                          dataSource.umShopPlanMaterieBomList[0]
                                            ?.key,
                                        ]
                                      : [],
                                },
                              },
                            ],
                          },
                        ],
                        totalCard = [...shopplanDetail, ...bottom];
                      dispatch({
                        type: "see",
                        dataSource,
                        detailStepData: dataSource?.umShopPlanProcessLine ?? {},
                        totalCard,
                      });
                    }
                  });
                }}
              >
                {row.shopPlanNo}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "工厂",
        dataIndex: "factoryName",
        key: "factoryName",
      },
      {
        title: "车间",
        dataIndex: "shopName",
        key: "shopName",
      },
      {
        title: "工艺路线编号",
        dataIndex: "processLineCode",
        key: "processLineCode",
        search: false,
      },
      {
        title: "工艺路线名称",
        dataIndex: "processLineName",
        key: "processLineName",
      },
      {
        title: "物料编号",
        dataIndex: "materieCode",
        key: "materieCode",
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
      },
      {
        title: "生产单位",
        dataIndex: "productionUnitName",
        key: "productionUnitName",
        search: false,
      },
      {
        title: "计划数量",
        dataIndex: "planNum",
        key: "planNum",
        search: false,
      },
      {
        title: "计划开始时间",
        dataIndex: "planStartDate",
        key: "planStartDate",
        search: false,
      },
      {
        title: "计划完成时间",
        dataIndex: "planEndDate",
        key: "planEndDate",
        search: false,
      },
      {
        title: "生产订单编号",
        dataIndex: "productionOrderNo",
        key: "productionOrderNo",
      },
      {
        title: "已排产数量",
        dataIndex: "scheduledProductionNum",
        key: "scheduledProductionNum",
        search: false,
      },
      {
        title: "完成数量",
        dataIndex: "finishNum",
        key: "finishNum",
        search: false,
      },
      {
        title: "车间计划状态",
        dataIndex: "statusName",
        key: "statusName",
        search: false,
      },
      {
        title: "排序号",
        dataIndex: "sortNo",
        key: "sortNo",
        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/omShopPlanMaterieBomTmp/queryTreeList"
            actionRef={actionRefs}
            extraparams={{ shopPlanId: 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/omShopPlanProcessLineStepTmp/queryTreeList"
                  actionRef={actionRefc}
                  pagination="false"
                  rowKey={"key"}
                  extraparams={{ id: tabKey }}
                ></AutoTable>
              </TabPane>
            ))}
          </Tabs>
        ),
      },
    ];
  function extraAction(text, record, _, action) {
    // status  0 待确认 1已确认 2 已撤回 3 生产中
    let ifs = record.status == 0 || record.status == 2,
      ifsc = record.status == 1;
    return [
      ifs &&
        getPrem("sysDepartment_save", action, "修改", () => {
          if (record.dataSources == 1) {
            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 });
          } else {
            doFetch({
              url: "/ngic-production/umShopPlan/queryDetailById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                let dataSource = res?.data?.data ?? {};
                for (let i in addFields) {
                  addFields[i].value = dataSource[i];
                  if (
                    i == "planStartDate" ||
                    i == "planEndDate" ||
                    i == "sortNo" ||
                    i == "description"
                  ) {
                    addFields[i].disabled = false;
                  } else {
                    addFields[i].disabled = true;
                  }
                }
                dispatch({
                  type: "editIssue",
                  fieldsc: addFields,
                  curitem: record,
                });
              }
            });
          }
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "确认", null, {
          title: "确认确认该车间计划？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umShopPlan/confirmById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifsc &&
        getPrem("sysDepartment_deleteById", action, "撤回", null, {
          title: "确认撤回该车间计划？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umShopPlan/withdrawById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
      ifs &&
        getPrem("sysDepartment_deleteById", action, "删除", null, {
          title: "确认删除该车间计划？",
          onConfirm: () => {
            doFetch({
              url: "/ngic-production/umShopPlan/deleteById",
              params: { id: record.id },
            }).then((res) => {
              if (res.code == "0000") {
                reload();
              }
            });
          },
        }),
    ];
  }
  function extraActions(text, record, index, action) {
    if (currentStep == 1 && record.parentKey == "0") {
      dispatch({ type: "changeExpand", expandedRowKeys: [record.key] });
    }
    return [
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "升序", () => {
          run({
            url: "/ngic-production/omShopPlanProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 1 },
          });
        }),
      currentStep == 2 &&
        record.parentKey == "0" &&
        getPrem("sysDepartment_deleteById", action, "降序", () => {
          run({
            url: "/ngic-production/omShopPlanProcessLineStepTmp/upDown",
            params: { id: record.key, stepSort: 2 },
          });
        }),
      ((currentStep == 1 && record.materieType == 2) ||
        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/omShopPlanMaterieBomTmp/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/omShopPlanMaterieBomTmp/deleteById"
                  : record.parentKey == 0
                  ? "/ngic-production/omShopPlanProcessLineStepTmp/deleteById"
                  : "/ngic-production/omShopPlanProcessLineStepProcedureTmp/deleteById",
              params: { id: record.key },
            });
          },
        }),
    ];
  }
  const next = () => {
    let newStep = currentStep + 1;
    if (currentStep == 0) {
      let editId =
        editType == "mastEdit" ? { shopPlanId: 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/omShopPlanTmp/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);
          }
        });
      });
    } else {
      dispatch({ type: "setCurrent", currentStep: newStep });
    }
    if (currentStep == 1) {
      doFetch({
        url: "/ngic-production/omShopPlanProcessLineTmp/queryByShopPlanId",
        params: { shopPlanId: orderId },
      }).then((res) => {
        if (res.code == "0000") {
          let data = res?.data?.data ?? {};
          dispatch({ type: "changeTableTep", tabeTep: [data] });
          dispatch({ type: "changeTabKey", tabKey: data?.id ?? "" });
        }
      });
    }
  };
  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/omShopPlanMaterieBomTmp/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/omShopPlanProcessLineStepProcedureTmp/queryAddProcedurePage",
        rowKey: "id",
        rowName: "workingProcedureName",
        extraparams: { id: tabKey },
      },
    };
    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 == "editIssue") {
      url = "/ngic-production/umShopPlan/save";
      params = {
        id: curitem.id,
        planStartDate: newfields.planStartDate,
        planEndDate: newfields.planEndDate,
        description: newfields.description,
        sortNo: newfields.sortNo,
      };
      doFetch({ url, params }).then((res) => {
        if (res.code == "0000") {
          reload();
          dispatch({ type: "closeBom" });
        }
      });
    } else {
      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,
          shopPlanId: orderId,
          parentId: curitem.key,
        };
        url = "/ngic-production/omShopPlanMaterieBomTmp/save";
      } else if (iftype.val == "editBom") {
        params = {
          numberUnits: newfields.numberUnits,
          workingProduceId: newfields.workingProduceId,
          workingFeedingId: newfields.workingFeedingId,
          id: curitem.key,
        };
        url = "/ngic-production/omShopPlanMaterieBomTmp/save";
      } else if (iftype.val == "addProcess") {
        newfields.procedureList = newfields.procedureList.map((it) => {
          return {
            workingProcedureId: it,
          };
        });
        url = "/ngic-production/omShopPlanProcessLineStepTmp/add";
        params = {
          ...newfields,
          shopPlanId: orderId,
          id: iftype.isTopRightAdd ? "" : curitem.key,
          processLineId: tabKey,
        };
      }
      run({ url, params });
    }
  };
  function getExpend(dataId) {
    doFetch({
      url: "/ngic-production/omShopPlanMaterieBomTmp/queryTreeList",
      params: { shopPlanId: 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/umShopPlan/queryList"
            : "/ngic-production/umShopPlan/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/omShopPlanTmp/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={900}
        style={{ position: "absolute" }}
        getContainer={false}
        maskClosable={false}
      >
        <InitForm
          fields={fieldsc}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          onChange={(changedValues, allValues) => {}}
          submitting={loading || !visible}
        ></InitForm>
      </Drawer>

      <Details
        title="车间计划详情"
        visible={detailsVisible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        bottomNode={
          <Card
            title={`工艺路线信息（所属工厂：${detailStepData.factoryName} | 所属车间：${detailStepData.shopName}）`}
            bordered={false}
            style={{ marginBottom: 16 }}
            bodyStyle={{ padding: "16px 10px" }}
          >
            <div className="gongyiStep">
              <Steps direction="vertical">
                {detailStepData?.shopPlanProcessLineStepList?.map((it, i) => {
                  return (
                    <Step
                      disabled={true}
                      key={i}
                      title={
                        <div style={{ width: "100%", display: "flex" }}>
                          <div className={styles.stepTitle}>
                            <Tooltip title={`步骤${i + 1}`}>
                              <span>{`步骤${i + 1}`}</span>
                            </Tooltip>
                          </div>
                        </div>
                      }
                      description={
                        it?.processLineStepProcedureList && (
                          <div style={{ width: "100%" }}>
                            <Row gutter={[12, 12]}>
                              {it?.processLineStepProcedureList?.map(
                                (item, j) => {
                                  return (
                                    <Col span={8} key={j}>
                                      <div
                                        style={{
                                          padding: 12,
                                          border: "1px solid #d9d9d9",
                                        }}
                                      >
                                        <div
                                          style={{
                                            display: "flex",
                                            flexDirection: "column",
                                            justifyContent: "center",
                                          }}
                                        >
                                          <Tooltip
                                            title={`工序编号：${item.workingProcedureCode}`}
                                          >
                                            <div
                                              className={styles.one}
                                              style={{ marginBottom: 12 }}
                                            >
                                              工序编号：
                                              {item.workingProcedureCode}
                                            </div>
                                          </Tooltip>
                                          <Tooltip
                                            title={`工序名称：${item.workingProcedureName}`}
                                          >
                                            <div className={styles.one}>
                                              工序名称：
                                              {item.workingProcedureName}
                                            </div>
                                          </Tooltip>
                                        </div>
                                      </div>
                                    </Col>
                                  );
                                }
                              )}
                            </Row>
                          </div>
                        )
                      }
                    />
                  );
                })}
              </Steps>
            </div>
          </Card>
        }
        {...detail}
      ></Details>
    </div>
  );
};
export default Shopplan;
