import React, { useState, 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 Details from "@/components/Details";
import { materielDetail } from "@/utils/detailTotalCard";
import InitForm from "@/components/InitForm";
import moment from "moment";
import TreeRender from "@/components/TreeRender";
import { useEffect } from "react";
import { storeselectionBoxAll } from "@/services/system.js";

const initState = {
    vs: false,
    fields: {},
    iftype: {},
    curitem: {},
    detail: {
      dataSource: {},
      totalCard: [],
    },
    visible: false,
    specificFileds: {},
    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,
      };
      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 "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: {},
      };
      break;
  }

  return newState;
}

const Materiel = (props) => {
  let actionRef = useRef(),
    ChildRef = null,
    [formRef] = Form.useForm(),
    [formRefs] = Form.useForm();
  const [materieTypeId, setmaterieTypeId] = useState();
  const [defaultSpecificFileds, setdefaultSpecificFileds] = useState();
  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,
      commonFields,
      defaultCommonFields,
      markKey,
    } = state,
    columns = [
      {
        title: "库位编码",
        dataIndex: "storePositionCode",
        key: "storePositionCode",
      },
      {
        title: "库位名称",
        dataIndex: "storePositionName",
        key: "storePositionName",
        // 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,
        //                 },
        //               ];
        //               dataSource.newqualityGuaranteePeriod =
        //                 dataSource.qualityGuaranteePeriod == 0 ||
        //                 dataSource.qualityGuaranteePeriod
        //                   ? dataSource.qualityGuaranteePeriod +
        //                     dataSource.qualityGuaranteePeriodUnitName
        //                   : null;
        //               let totalCard = materielDetail.concat(itemCol);
        //               dispatch({ type: "see", dataSource, totalCard });
        //             }
        //           });
        //         }}
        //       >
        //         {row.materieName}
        //       </a>
        //     </Tooltip>
        //   );
        // },
      },
      {
        title: "所属仓库",
        dataIndex: "storeName",
        key: "storeName",
        // valueType: "select",
        // options: {
        //   database: storeselectionBoxAll,
        // },
      },
      {
        title: "所属库区",
        dataIndex: "storeAreaName",
        key: "storeAreaName",
        // options: {
        //   database: () =>
        //     doFetch({
        //       url: "/ngic-base-business/sysDic/queryMaterieControlSelect",
        //     }),
        //   params: {},
        // },
        // valueType: "select",
        // formItemProps: {
        //   name: "materieControl",
        // },
      },
      {
        title: "排",
        dataIndex: "row",
        key: "row",
        valueType: "digit",
        search: false,
      },
      {
        title: "列",
        dataIndex: "line",
        key: "line",
        valueType: "digit",
        search: false,
      },
      {
        title: "层",
        dataIndex: "level",
        key: "level",
        valueType: "digit",
        search: false,
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        search:false,
        render: (_, row) => <span>{row?.status == "1" ? "启用" : "禁用"}</span>,
      },
      {
        title: "更新人",
        dataIndex: "updateUserName",
        key: "updateUserName",
        search: false,
      },

      {
        title: "更新时间",
        dataIndex: "updateTime",
        key: "updateTime",
        search: false,
      },
      {
        title: "是否为移库仓位",
        dataIndex: "isMovePosition",
        key: "isMovePosition",
        valueType: "select",
        search: false,
        options: [
          {
            value: "1",
            label: "是",
          },
          {
            value: "2",
            label: "否",
          },
        ],
        render: (_, row) => {
          return row?.isMovePosition ? "是" : "否";
        },
      },

      {
        title: "操作",
        dataIndex: "option_dataindex",
        key: "option_dataindex",
        valueType: "option",
        width: 160,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];
  useEffect(() => {
    doFetch({
      url: "/ngic-workmanship/pmMaterieChar/queryCommonList",
      params: {},
    }).then((res) => {
      setdefaultSpecificFileds(res?.data?.dataList);
    });
  }, []);

  function extraAction(text, record, _, action) {
    return [
      getPrem("sysDepartment_save", action, "修改", () => {
        doFetch({
          url: "/ngic-auth/sysStorePosition/queryById",
          params: { id: record.id },
        }).then((res) => {
          if (res.code == "0000") {
            let data = res?.data?.data ?? {};
            console.log(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,
              //   ];
              // }
            }
            console.log(defaultFields);
            let all = async () => {
              let common = await doFetch({
                url: "/ngic-workmanship/pmMaterieChar/queryCommonList",
                params: { id: record.id },
              });

              return {
                commonData: common?.data?.dataList,
              };
            };
            all().then((res) => {
              let commonDataFields = formatFieds(
                  res?.commonData,
                  "common"
                )?.obj,
                newCommonData = formatFieds(res?.commonData, "common")?.data;
              console.log(defaultFields);
              dispatch({
                type: "edit",
                fields: defaultFields,
                curitem: record,
                commonFields: commonDataFields,
                specificFileds: { ...commonDataFields },
                defaultCommonFields: newCommonData,
              });
              setdefaultSpecificFileds([...newCommonData]);
            });
          }
        });
      }),
      getPrem("sysDepartment_deleteById", action, "删除", null, {
        title: "确认删除该库位？",
        onConfirm: () => {
          run({
            url: "/ngic-auth/sysStorePosition/deleteById",
            params: { id: record.id },
          });
        },
      }),
    ];
  }
  let saveData = () => {
    //新增&修改
    let difrid = iftype.val != "add" ? { id: curitem.id } : {},
      params,
      url;
    if (iftype.val != "bom") {
      formRef
        .validateFields()
        .then((firstValues) => {
          formRefs
            .validateFields()
            .then((secondFields) => {
              let secondFieldsKeys = Object.keys(secondFields);
              let materieProductUnitList =
                firstValues?.materieProductUnitList?.map((it) => {
                  return {
                    productionUnit: it.productionUnit,
                    conversionRate: it.conversionRate,
                  };
                });
              for (let i in firstValues) {
                if (firstValues[i] === undefined) {
                  firstValues[i] = null;
                }
              }
              params = {
                ...firstValues,
                ...difrid,
                materieProductUnitList,
              };
              url = "/ngic-auth/sysStorePosition/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")}
      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 == 'status') {
                defaultFields[i].value = 1;
              }
              if (
                i == "serialNumberRuleId" ||
                i == "labelTemplateId" ||
                i == "processLineId"
              ) {
                defaultFields[i].required = false;
              }
              // if (i == "issueType") {
              //   defaultFields[i].value = 1;
              // }
            }
            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,
    };
  }
  useEffect(() => {
    console.log("123", materieTypeId);
  }, [materieTypeId]);
  return (
    <div>
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        path="/ngic-auth/sysStorePosition/queryList"
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        childposition="left"
        extraparams={{ ...materieTypeId }}
        x={600}
      >
        <div
          style={{
            width: 260,
            flexShrink: 0,
            marginTop: -4,
            borderRight: "1px solid #f0f0f0",
            paddingRight: 12,
            marginRight: 12,
          }}
        >
          <TreeRender
            url="/ngic-auth/sysFactory/queryFactoryStoreTree"
            // deleteurl="/ngic-auth/sysFactory/deleteById"
            // saveurl="/ngic-auth/sysFactory/save"
            onselected={(vals, e, alldata) => {
              console.log(e?.node);
              const valType = e?.node?.level;
              let obj = {};
              if (valType == 1) {
                // 工厂
                obj.factoryId = vals[0] ?? "";
              } else if (valType == 2) {
                obj.storeId = vals[0] ?? "";
              } else if (valType == 3) {
                obj.storeAreaId = vals[0] ?? "";
              }
              console.log(obj);
              setmaterieTypeId(obj);
            }}
          />
        </div>
      </AutoTable>
      <Drawer
        title={iftype.title}
        visible={vs}
        onClose={() => dispatch({ type: "close" })}
        footer={false}
        destroyOnClose={true}
        getContainer={false}
        style={{ position: "absolute" }}
        width={"100%"}
      >
        <InitForm
          formRef={formRef}
          fields={fields}
          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;
