import React, { useEffect, useRef, useReducer } from "react";
import { Button, Tooltip, Row, Divider, Drawer, Form, message } from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { useRequest } from "umi";
import defaultFields from "./fields";
import { doFetch } from "@/utils/doFetch";
import DrawInitForm from "@/components/DrawInitForm";
import Details from "@/components/Details";
import { materielDetail } from "@/utils/detailTotalCard";
import InitForm from "@/components/InitForm";
import moment from "moment";
import Coltext from "@/components/Coltext";
import RenderItemType from "@/components/RenderItemType";
const initState = {
    vs: false,
    fields: {},
    iftype: {},
    curitem: {},
    detail: {
      dataSource: {},
      totalCard: [],
    },
    visible: false,
    specificFileds: {},
    defaultSpecificFileds: [],
    commonFields: {},
    defaultCommonFields: [],
  },
  otherBasic = {
    materieCode: "物料编号",
    materieName: "物料名称",
    materieTypeName: "物料类别",
    productionUnitName: "生产单位（主）",
    processLineName: "工艺路线",
  };
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "add":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "新增物料",
          val: type,
        },
        fields: { ...action.fields },
        commonFields: action.commonFields,
        specificFileds: action.specificFileds,
      };
      break;
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑物料",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
        commonFields: action.commonFields,
        specificFileds: action.specificFileds,
        defaultCommonFields: action.defaultCommonFields,
        defaultSpecificFileds: action.defaultSpecificFileds,
      };
      break;
    case "bom":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "编辑物料BOM",
          val: type,
        },
        fields: { ...action.fields },
        curitem: action.curitem,
        markKey: action.markKey,
      };
      break;
    case "see":
      newState = {
        ...state,
        detail: {
          dataSource: action.dataSource,
          totalCard: action.totalCard,
        },
        visible: true,
      };
      break;
    case "changeSpecificFileds":
      newState = {
        ...state,
        specificFileds: action.specificFileds,
      };
      break;
    case "changeFields":
      newState = {
        ...state,
        fields: action.fields,
      };
      break;
    case "changeDefaultSpecificFileds":
      newState = {
        ...state,
        defaultSpecificFileds: action.defaultSpecificFileds,
      };
      break;
    case "changeCommonFields":
      newState = {
        ...state,
        commonFields: action.commonFields,
      };
      break;
    case "changeDefaultCommonFields":
      newState = {
        ...state,
        defaultCommonFields: action.defaultCommonFields,
      };
      break;
    case "close":
      newState = {
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
        detail: {
          dataSource: {},
          totalCard: [],
        },
        visible: false,
        specificFileds: {},
        defaultSpecificFileds: [],
      };
      break;
  }

  return newState;
}

const Materiel = (props) => {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm(),
    [formRefs] = Form.useForm();
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          reload();
          dispatch({ type: "close" });
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    {
      vs,
      fields,
      iftype,
      curitem,
      detail,
      visible,
      specificFileds,
      defaultSpecificFileds,
      commonFields,
      defaultCommonFields,
      markKey,
    } = state,
    columns = [
      {
        title: "物料编号",
        dataIndex: "materieCode",
        key: "materieCode",
      },
      {
        title: "物料名称",
        dataIndex: "materieName",
        key: "materieName",
        render: (_, row) => {
          return (
            <Tooltip title={row.materieName}>
              <a
                className="table-cell"
                onClick={() => {
                  doFetch({
                    url: "/ngic-workmanship/pmMaterie/queryDetailById",
                    params: { id: row.id },
                  }).then((res) => {
                    if (res.code == "0000") {
                      let dataSource = res?.data?.data ?? {},
                        specials = res?.data?.data?.materieCharList ?? [];
                      let newData = formatFieds(specials, "special")?.data;

                      let newSpecialData = newData.map((it) => {
                        dataSource[it.fieldsKey] = it.fieldRealValue;
                        return {
                          title: it.fieldName,
                          key: it.fieldsKey,
                        };
                      });
                      let itemCol = [
                        {
                          cardTitle: "特殊属性",
                          itemData: newSpecialData,
                        },
                      ];
                      let totalCard = materielDetail.concat(itemCol);
                      dispatch({ type: "see", dataSource, totalCard });
                    }
                  });
                }}
              >
                {row.materieName}
              </a>
            </Tooltip>
          );
        },
      },
      {
        title: "生产单位(主)",
        dataIndex: "productionUnitName",
        key: "productionUnitName",
      },
      {
        title: "物料类别",
        dataIndex: "materieTypeName",
        key: "materieTypeName",
        options: [
          {
            label: "自制件",
            value: 0,
          },
          {
            label: "采购件",
            value: 1,
          },
          {
            label: "虚拟件",
            value: 2,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "materieType",
        },
      },
      {
        title: "物料管控",
        dataIndex: "materialControlName",
        key: "materialControlName",
        options: [
          {
            label: "单品管控",
            value: 0,
          },
          {
            label: "批次管控",
            value: 1,
          },
        ],
        valueType: "select",
        formItemProps: {
          name: "materialControl",
        },
        search: false,
      },
      {
        title: "工艺线路",
        dataIndex: "processLineName",
        key: "processLineName",
      },
      {
        title: "描述",
        dataIndex: "remark",
        key: "remark",
        search: false,
      },
      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 275,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];
  function extraAction(text, record, _, action) {
    let ifs = record.materieType != 1;
    return [
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-workmanship/pmMaterie/queryUpdateById",
          params: { id: record.id },
        }).then((res) => {
          if (res.code == "0000") {
            let data = res?.data?.data ?? {};
            let newArr =
              data?.materieProductUnitList?.map((it) => {
                return {
                  productionUnit: it.productionUnit,
                  productionUnitType: it.productionUnitType,
                  id: it.id,
                };
              }) ?? [];

            for (let i in defaultFields) {
              defaultFields[i].value = data[i];
              if (i == "unitList") {
                defaultFields[i].value = [
                  {
                    id: moment().valueOf(),
                    productionUnit: data?.productionUnit,
                    productionUnitType: data?.productionUnitType,
                  },
                  ...newArr,
                ];
              }
            }

            let all = async () => {
              let common = await doFetch({
                  url: "/ngic-workmanship/pmMaterieChar/queryCommonList",
                  params: { id: record.id },
                }),
                other = await doFetch({
                  url: "/ngic-workmanship/pmMaterieChar/queryListBykey",
                  params: {
                    id: record.id,
                    materialControl: record.materialControl,
                  },
                });

              return {
                commonData: common?.data?.dataList,
                otherData: other?.data?.dataList,
              };
            };
            all().then((res) => {
              let commonDataFields = formatFieds(
                  res?.commonData,
                  "common"
                )?.obj,
                otherDataFields = formatFieds(res?.otherData, "other")?.obj,
                newCommonData = formatFieds(res?.commonData, "common")?.data,
                newOtherData = formatFieds(res?.otherData, "other")?.data;
              dispatch({
                type: "edit",
                fields: defaultFields,
                curitem: record,
                commonFields: commonDataFields,
                specificFileds: { ...commonDataFields, ...otherDataFields },
                defaultCommonFields: newCommonData,
                defaultSpecificFileds: [...newCommonData, ...newOtherData],
              });
            });
          }
        });
      }),
      ifs &&
        getPrem("sysDepartment_save", action, "编辑物料BOM", () => {
          let all = async () => {
            let mark = await doFetch({
                url: "/ngic-base-business/bmSpecialSet/queryByMark",
                params: { mark: "materiel_bom" },
              }),
              bom = await doFetch({
                url: "/ngic-workmanship/pmMaterieBom/queryByMaterieParentId",
                params: { materieParentId: record.id },
              });
            return {
              markKey: mark?.data?.value,
              bomData: bom?.data?.dataList,
            };
          };
          all().then((res) => {
            const { markKey, bomData } = res;
            let fields = {
              materieBomList: {
                value: JSON.parse(JSON.stringify(bomData)),
                title: "BOM信息",
                type: "table",
                col: { span: 14 },
                name: ["materieBomList"],
                required: false,
                columns: [
                  {
                    title: "物料编号",
                    dataIndex: "materieCode",
                    key: "materieCode",
                    search: false,
                    ellipsis: true,
                    editable: false,
                  },
                  {
                    title: "物料名称",
                    dataIndex: "materieName",
                    key: "materieName",
                    search: false,
                    ellipsis: true,
                    editable: false,
                  },
                  {
                    title: "生产单位(主)",
                    dataIndex: "productionUnitName",
                    key: "productionUnitName",
                    search: false,
                    ellipsis: true,
                    editable: false,
                  },
                  {
                    title: "物料类别",
                    dataIndex: "materieTypeName",
                    key: "materieTypeName",
                    search: false,
                    ellipsis: true,
                    editable: false,
                  },
                  {
                    title: "台份量",
                    dataIndex: "numberUnits",
                    key: "numberUnits",
                    editable: true,
                    renderFormItem: (
                      item,
                      { fieldProps, formItemProps },
                      form
                    ) => {
                      return (
                        <RenderItemType
                          {...fieldProps}
                          type={"inputnumber"}
                          rowKey={item.entry.rowKey}
                        />
                      );
                    },
                    width: 100,
                    formItemProps: (form, config) => {
                      return {
                        rules: [{ required: true, message: "此项为必填项" }],
                      };
                    },
                  },
                  {
                    title: "产出工序",
                    dataIndex: "workingProduceId",
                    key: "workingProduceId",
                    valueType: "select",
                    width: 150,
                    formItemProps: (form, config) => {
                      return {
                        rules:
                          markKey == 2 || config.entry.materieType == 1
                            ? []
                            : [{ required: true, message: "此项为必填项" }],
                      };
                    },
                    renderFormItem: (item, { fieldProps }, form) => {
                      if (item.entry.materieType == 1 || markKey == 2) {
                        return <></>;
                      } else {
                        return (
                          <RenderItemType
                            {...fieldProps}
                            type={"select"}
                            selectarr={item.entry.workingProduceList ?? []}
                            rowKey={item.entry.rowKey}
                          />
                        );
                      }
                    },
                  },
                  {
                    title: "投料工序",
                    dataIndex: "workingFeedingId",
                    key: "workingFeedingId",
                    valueType: "select",
                    width: 150,
                    formItemProps: (form, config) => {
                      return {
                        rules:
                          markKey == 2
                            ? []
                            : [{ required: true, message: "此项为必填项" }],
                      };
                    },
                    renderFormItem: (item, { fieldProps }, form) => {
                      if (markKey == 2) {
                        return <></>;
                      } else {
                        return (
                          <RenderItemType
                            {...fieldProps}
                            type={"select"}
                            selectarr={item.entry.workingFeedingList ?? []}
                            rowKey={item.entry.rowKey}
                          />
                        );
                      }
                    },
                  },
                  {
                    title: "操作",
                    valueType: "option",
                    width: 70,
                    render: (text, record, _, action) => [
                      <a key="delete">删除</a>,
                    ],
                  },
                ],
                rowKey: "rowKey",
                recordCreatorProps: "false",
              },
              materieList: {
                value: [],
                type: "checktable",
                title: "物料信息",
                name: ["materieList"],
                required: false,
                columns: [
                  {
                    title: "物料编号",
                    dataIndex: "materieCode",
                    key: "materieCode",
                  },
                  {
                    title: "物料名称",
                    dataIndex: "materieName",
                    key: "materieName",
                  },
                  {
                    title: "生产单位(主)",
                    dataIndex: "productionUnitName",
                    key: "productionUnitName",
                    search: false,
                  },
                  {
                    title: "物料类别",
                    dataIndex: "materieTypeName",
                    key: "materieTypeName",
                    search: false,
                  },
                  {
                    title: "描述",
                    dataIndex: "remark",
                    key: "remark",
                    search: false,
                  },
                ],
                editable: true,
                path: "/ngic-workmanship/pmMaterie/queryBomById",
                extraparams: { id: record.id },
                rowKey: "id",
                rowName: "materieName",
                tabletype: "checkbox",
                pageSize: 10,
                col: { span: 10 },
              },
            };
            dispatch({ type: "bom", fields, curitem: record, markKey });
          });
        }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该物料？",
        onConfirm: () => {
          run({
            url: "/ngic-workmanship/pmMaterie/deleteById",
            params: { id: record.id },
          });
        },
      }),
    ];
  }
  let saveData = () => {
    //新增&修改
    let difrid = iftype.val != "add" ? { id: curitem.id } : {},
      params,
      url;
    if (iftype.val != "bom") {
      let firstValues = formRef?.getFieldsValue(),
        secondFields = formRefs?.getFieldsValue();
      formRef
        .validateFields()
        .then((res) => {
          formRefs
            .validateFields()
            .then((res) => {
              const { unitList } = firstValues;
              let materieProductUnitList = [],
                materieCharList;
              unitList?.map((it, i) => {
                if (i != 0) {
                  materieProductUnitList.push({
                    productionUnit: it.productionUnit,
                    productionUnitType: it.productionUnitType,
                  });
                }
              });
              let productionUnit = unitList[0].productionUnit,
                productionUnitType = unitList[0].productionUnitType;
              let secondFieldsKeys = Object.keys(secondFields);
              materieCharList = defaultSpecificFileds.map((it) => {
                if (secondFieldsKeys.indexOf(it.fieldsKey) != -1) {
                  it.fieldRealValue = secondFields[it.fieldsKey];
                }
                const el = {
                  fieldType: it.fieldType,
                  fieldTypeName: it.fieldTypeName,
                  fieldCondName: it.fieldCondName,
                  fieldCondKey: it.fieldCondKey,
                  optCondName: it.optCondName,
                  optCondKey: it.optCondKey,
                  fieldId: it.fieldId,
                  fieldName: it.fieldName,
                  fieldChar: it.fieldChar,
                  fieldCharName: it.fieldCharName,
                  fieldCharValue: it.fieldCharValue,
                  fieldRealValue: it.fieldRealValue,
                  valueList: it.valueList,
                };
                return el;
              });
              delete firstValues.unitList;
              params = {
                ...firstValues,
                materieProductUnitList,
                materieCharList,
                productionUnit,
                productionUnitType,
                ...difrid,
              };
              url = "/ngic-workmanship/pmMaterie/save";
              run({ url, params });
            })
            .catch((error) => {});
        })
        .catch((error) => {});
    } else {
      url = "/ngic-workmanship/pmMaterie/saveMaterieBom";
      let firstValues = formRef?.getFieldsValue();
      let materieBomList = firstValues?.materieBomList?.map((it, i) => {
        return {
          materieId: it.id,
          materieName: it.materieName,
          materieCode: it.materieCode,
          materieType: it.materieType,
          numberUnits: it.numberUnits,
          workingProduceId: it.workingProduceId,
          workingFeedingId: it.workingFeedingId,
          rowKey: String(i),
          productionUnitName: it.productionUnitName,
        };
      });
      params = {
        materieBomList,
        ...difrid,
      };
      run({ url, params });
    }
  };
  let extrarender = [
    <Button
      disabled={!getPrem("sysDepartment_save", "ifs")}
      style={{ marginRight: 15 }}
      type="primary"
      onClick={() => {
        doFetch({
          url: "/ngic-workmanship/pmMaterieChar/queryCommonList",
          params: {},
        }).then((res) => {
          if (res.code == "0000") {
            let data = res?.data?.dataList,
              otherFields = formatFieds(data, "common")?.obj,
              newData = formatFieds(data, "common")?.data;
            for (let i in defaultFields) {
              defaultFields[i].value = null;
              defaultFields[i].disabled = false;
              if (
                i == "materialControl" ||
                i == "serialNumberRuleId" ||
                i == "labelTemplateId" ||
                i == "processLineId"
              ) {
                defaultFields[i].required = false;
              }
            }
            dispatch({
              type: "add",
              fields: defaultFields,
              commonFields: otherFields,
              specificFileds: otherFields,
            });
            dispatch({
              type: "changeDefaultCommonFields",
              defaultCommonFields: newData,
            });
          }
        });
      }}
    >
      新增
    </Button>,
  ];
  function formatFieds(data, type) {
    let obj = {};
    for (let i = 0; i < data.length; i++) {
      let item = data[i],
        fieldsKey = type + "field" + i;
      item["fieldsKey"] = fieldsKey;
      if (item.fieldChar == 1) {
        obj[fieldsKey] = {
          value: item?.fieldRealValue ?? "",
          title: item.fieldName,
          name: [fieldsKey],
          required: false,
          type: "input",
        };
      } else {
        obj[fieldsKey] = {
          value:
            item?.fieldRealValue == 0 || item?.fieldRealValue
              ? item?.fieldRealValue
              : item.fieldChar == 4
              ? []
              : "",
          title: item.fieldName,
          name: [fieldsKey],
          required: false,
          type: item.fieldChar == 3 ? "radio" : "select",
          options: item.valueList,
          multiple: item.fieldChar == 4 ? true : false,
        };
      }
    }
    return {
      obj,
      data,
    };
  }
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-workmanship/pmMaterie/queryList"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
      ></AutoTable>
      <Drawer
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        getContainer={false}
        style={{ position: "absolute" }}
        width={"100%"}
      >
        {iftype.val == "bom" ? (
          <>
            <Row gutter={[16, 10]}>
              {Object.keys(otherBasic).map((it) => {
                return (
                  <Coltext
                    label={otherBasic[it]}
                    value={curitem[it]}
                    key={it}
                  />
                );
              })}
            </Row>
            <Divider />
            <Button
              type="primary"
              style={{ marginBottom: 15 }}
              onClick={() => {
                let fieldsData = formRef.getFieldValue("materieBomList") ?? [],
                  leftData = formRef.getFieldValue("materieList") ?? [];
                fieldsData = JSON.parse(JSON.stringify(fieldsData));
                leftData = JSON.parse(JSON.stringify(leftData));
                let newDatas =
                  [...fieldsData, ...leftData].map((it, i) => {
                    it.rowKey = String(i);
                    return it;
                  }) ?? [];
                formRef.setFieldsValue({
                  materieBomList: [...newDatas],
                  materieList: [],
                });
                // let newFields = JSON.parse(JSON.stringify(fields));
                // for (let i in newFields) {
                //     if (i == "materieBomList") {
                //         newFields[i].columns[4].renderFormItem = (item, { fieldProps, formItemProps }, form) => {
                //             return <RenderItemType {...fieldProps} type={'inputnumber'} rowKey={item.entry.rowKey} />;
                //         };
                //         newFields[i].columns[5].renderFormItem = (item, { fieldProps }, form) => {
                //             if (item.entry.materieType == 1 || markKey == 2) {
                //                 return (
                //                     <></>
                //                 );
                //             } else {
                //                 return <RenderItemType
                //                     {...fieldProps}
                //                     type={'select'}
                //                     selectarr={item.entry.workingProduceList ?? []}
                //                     rowKey={item.entry.rowKey}
                //                 />
                //             }
                //         };
                //         newFields[i].columns[6].renderFormItem = (item, { fieldProps }, form) => {
                //             if (markKey == 2) {
                //                 return (
                //                     <></>
                //                 );
                //             } else {
                //                 return <RenderItemType
                //                     {...fieldProps}
                //                     type={'select'}
                //                     selectarr={item.entry.workingFeedingList ?? []}
                //                     rowKey={item.entry.rowKey}
                //                 />
                //             }
                //         };
                //         newFields[i].value = [...newDatas]
                //     }
                // }
                // dispatch({ type: "changeFields", fields: { ...newFields } });
              }}
            >
              添加至Bom信息
            </Button>
            <InitForm
              formRef={formRef}
              fields={fields}
              onChange={(changedValues, allValues) => {}}
              actions={() => {
                return null;
              }}
            ></InitForm>
          </>
        ) : (
          <>
            <InitForm
              formRef={formRef}
              fields={fields}
              onChange={(changedValues, allValues) => {
                for (let i in changedValues) {
                  if (i == "materialControl") {
                    doFetch({
                      url: "/ngic-workmanship/pmMaterieChar/queryListBykey",
                      params: {
                        materialControl: changedValues[i],
                        id: iftype.val == "edit" ? curitem.id : "",
                      },
                    }).then((res) => {
                      if (res.code == "0000") {
                        let data = res?.data?.dataList,
                          otherFields = formatFieds(data, "other")?.obj,
                          newData = formatFieds(data, "other")?.data;
                        dispatch({
                          type: "changeDefaultSpecificFileds",
                          defaultSpecificFileds: [
                            ...defaultCommonFields,
                            ...newData,
                          ],
                        });
                        dispatch({
                          type: "changeSpecificFileds",
                          specificFileds: { ...commonFields, ...otherFields },
                        });
                      }
                    });
                  }
                  if (i == "materieType") {
                    for (let j in fields) {
                      if (
                        j == "materialControl" ||
                        j == "serialNumberRuleId" ||
                        j == "processLineId" ||
                        j == "labelTemplateId"
                      ) {
                        if (changedValues[i] == 0) {
                          fields[j].required = true;
                          dispatch({ type: "changeFields", fields });
                        } else {
                          fields[j].required = false;
                          dispatch({ type: "changeFields", fields });
                        }
                      }
                    }
                  }
                }
              }}
              actions={() => {
                return null;
              }}
            ></InitForm>
            <div style={{ fontSize: 16, fontWeight: "bold", marginBottom: 15 }}>
              特定属性
            </div>
            <InitForm
              formRef={formRefs}
              fields={specificFileds}
              onChange={(changedValues, allValues) => {}}
              actions={() => {
                return null;
              }}
            ></InitForm>
          </>
        )}
        <Button
          style={{ width: "100%" }}
          type="primary"
          size="large"
          loading={loading || !vs}
          onClick={() => saveData()}
        >
          提交
        </Button>
      </Drawer>
      <Details
        title="物料详情"
        visible={visible}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        width={"100%"}
        {...detail}
      ></Details>
    </div>
  );
};
export default Materiel;
