import React, { useEffect, useReducer, useRef } from "react";
import {
  Button,
  Drawer,
  message,
  Form,
  Popconfirm,
  Switch,
  Tabs,
  Card,
  Row,
  Col,
  Tooltip,
  Checkbox,
  Divider,
} from "antd";
import AutoTable from "@/components/AutoTable";
import getPrem from "@/utils/getPrem"; //权限判断fn
import InitForm from "@/components/InitForm";
import { useRequest } from "umi";
import { waitFields, schedulingFields, tableFields } from "./fields";
import moment from "moment";
import { doFetch } from "@/utils/doFetch";
import {
  productionLineSelectByShop,
  shiftSelectByShopId,
} from "@/services/system";
const CheckboxGroup = Checkbox.Group;
const initState = {
  schedulingLeftData: [],
  schedulingCheckedData: [],
  searchLoading: false,
  indeterminate: false,
  topfields: {},
  bottomfields: {},
  checkAll: false,
  lastFields: {},
  addloading: false,
};
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "changeLeftData":
      newState = {
        ...state,
        schedulingLeftData: action.schedulingLeftData,
      };
      break;
    case "changeSearchLoading":
      newState = {
        ...state,
        searchLoading: action.searchLoading,
      };
      break;
    case "checkItem":
      newState = {
        ...state,
        indeterminate: action.indeterminate,
        schedulingCheckedData: action.schedulingCheckedData,
        checkAll: action.checkAll,
      };
      break;
    case "checkAllData":
      newState = {
        ...state,
        indeterminate: false,
        schedulingCheckedData: action.schedulingCheckedData,
        checkAll: action.checked,
      };
      break;
    case "changetopfields":
      newState = {
        ...state,
        topfields: action.topfields,
      };
      break;
    case "changebottomfields":
      newState = {
        ...state,
        bottomfields: action.bottomfields,
      };
      break;
    case "changeaddloading":
      newState = {
        ...state,
        addloading: action.addloading,
      };
      break;
    case "changelastFields":
      newState = {
        ...state,
        lastFields: action.lastFields,
      };
      break;
    case "close":
      newState = {
        schedulingLeftData: [],
        schedulingCheckedData: [],
        searchLoading: false,
        indeterminate: false,
        topfields: {},
        bottomfields: {},
        checkAll: false,
        lastFields: {},
        addloading: false,
      };
      break;
  }

  return newState;
}

const Scheduling = ({ reset, schedulingVisible }) => {
  const [state, dispatch] = useReducer(reducer, initState),
    {
      schedulingLeftData,
      schedulingCheckedData,
      topfields,
      bottomfields,
      searchLoading,
      indeterminate,
      checkAll,
      lastFields,
      addloading,
    } = state,
    [leftFormRef] = Form.useForm(),
    [rightFormRef] = Form.useForm(),
    [tableFormRef] = Form.useForm();
  useEffect(() => {
    dispatch({ type: "changetopfields", topfields: { ...waitFields } });
    dispatch({
      type: "changebottomfields",
      bottomfields: { ...schedulingFields },
    });
    for (let i in tableFields) {
      tableFields[i].value = [];
    }
    dispatch({ type: "changelastFields", lastFields: { ...tableFields } });
  }, []);
  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      if (result.code == "0000") {
        reset && reset();
        dispatch({ type: "close" });
      }
    },
  });
  return (
    <div style={{ display: "flex", height: "100%" }}>
      <div
        style={{
          flex: 1,
          height: "100%",
          display: "flex",
          flexDirection: "column",
          width: "100%",
          overflow: "hidden",
        }}
      >
        <div>
          <InitForm
            fields={topfields}
            submitData={(values, fn) => {}}
            onChange={(changedValues, allValues) => {
              for (let i in changedValues) {
                if (i == "shopId") {
                  for (let j in schedulingFields) {
                    if (!changedValues[i]) {
                      if (j == "productionLineId" || j == "shiftId") {
                        schedulingFields[j].options = [];
                        rightFormRef.setFieldsValue({ [j]: "" });
                      }
                    } else {
                      if (j == "productionLineId") {
                        schedulingFields[j].options = {
                          database: productionLineSelectByShop,
                          params: {
                            shopId: changedValues[i],
                          },
                        };
                      }
                      if (j == "shiftId") {
                        schedulingFields[j].options = {
                          database: shiftSelectByShopId,
                          params: {
                            shopId: changedValues[i],
                          },
                        };
                      }
                    }
                  }
                  dispatch({
                    type: "changebottomfields",
                    bottomfields: { ...schedulingFields },
                  });
                }
              }
            }}
            actions={(form, submitBtn) => {
              return (
                <Button
                  loading={searchLoading}
                  style={{ marginLeft: 12 }}
                  type="primary"
                  onClick={() => {
                    form
                      .validateFields()
                      .then((values) => {
                        dispatch({
                          type: "changeSearchLoading",
                          searchLoading: true,
                        });
                        let newFields = JSON.parse(JSON.stringify(values));
                        newFields.dateTimeList =
                          newFields.dateTimeList?.length > 0
                            ? [
                                moment(newFields.dateTimeList[0]).format(
                                  "YYYY-MM-DD"
                                ),
                                moment(newFields.dateTimeList[1]).format(
                                  "YYYY-MM-DD"
                                ),
                              ]
                            : [];
                        doFetch({
                          url: "/ngic-production/emPlanOrder/querySchedulingList",
                          params: { ...newFields },
                        }).then((res) => {
                          if (res.code == "0000") {
                            let data = res?.data?.dataList ?? [];
                            dispatch({
                              type: "changeLeftData",
                              schedulingLeftData: data,
                            });
                            dispatch({
                              type: "checkAllData",
                              schedulingCheckedData: [],
                              checked: false,
                            });
                            for (let i in tableFields) {
                              tableFields[i].value = [];
                              tableFormRef.setFieldsValue({ [i]: [] });
                            }
                            dispatch({
                              type: "changelastFields",
                              lastFields: { ...tableFields },
                            });
                            for (let i in schedulingFields) {
                              schedulingFields[i].value = "";
                              rightFormRef.setFieldsValue({ [i]: "" });
                            }
                            dispatch({
                              type: "changebottomfields",
                              bottomfields: { ...schedulingFields },
                            });
                          }
                          dispatch({
                            type: "changeSearchLoading",
                            searchLoading: false,
                          });
                        });
                      })
                      .catch((error) => {});
                  }}
                >
                  查询
                </Button>
              );
            }}
            formRef={leftFormRef}
          ></InitForm>
        </div>
        <div
          style={{
            marginTop: 12,
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <div>待排产计划</div>
          <Checkbox
            indeterminate={indeterminate}
            checked={checkAll}
            onChange={(e) => {
              dispatch({
                type: "checkAllData",
                schedulingCheckedData: e.target.checked
                  ? [...schedulingLeftData]
                  : [],
                checked: e.target.checked,
              });
            }}
          >
            全选
          </Checkbox>
        </div>
        <div
          className="scheduling"
          style={{
            flex: 1,
            overflowY: "auto",
            overflowX: "hidden",
            width: "100%",
          }}
        >
          <CheckboxGroup
            value={schedulingCheckedData.map((it) => it.id)}
            style={{ width: "100%" }}
            onChange={(list) => {
              dispatch({
                type: "checkItem",
                indeterminate:
                  !!list.length && list.length < schedulingLeftData.length,
                schedulingCheckedData:
                  list.length == 0
                    ? []
                    : schedulingLeftData.filter(
                        (it) => list.indexOf(it.id) > -1
                      ),
                checkAll: list.length == schedulingLeftData.length,
              });
            }}
          >
            {schedulingLeftData.map((it) => {
              return (
                <div
                  key={it.id}
                  style={{
                    width: "100%",
                    border: "1px solid #d9d9d9",
                    borderRadius: 4,
                    padding: 6,
                    marginTop: 12,
                  }}
                >
                  <Checkbox value={it.id} style={{ width: "100%" }}>
                    <div style={{ width: "100%", overflow: "hidden" }}>
                      <Tooltip title={`车间计划编号：${it.shopPlanNo}`}>
                        <div className="oneText" style={{ marginBottom: 2 }}>
                          车间计划编号：{it.shopPlanNo}
                        </div>
                      </Tooltip>
                      <Tooltip
                        title={`物料：${it.materieCode}-${it.materieName}-${it.productionUnitName}`}
                      >
                        <div className="oneText" style={{ marginBottom: 2 }}>
                          物料：
                          {`${it.materieCode}-${it.materieName}-${it.productionUnitName}`}
                        </div>
                      </Tooltip>
                      <Tooltip title={`未排数：${it.unscheduledQuantity}`}>
                        <div className="oneText" style={{ marginBottom: 2 }}>
                          未排数：{it.unscheduledQuantity}
                        </div>
                      </Tooltip>
                      <Tooltip
                        title={`计划时间：${it.planStartDate}~${it.planEndDate}`}
                      >
                        <div className="oneText">
                          计划时间：{`${it.planStartDate}~${it.planEndDate}`}
                        </div>
                      </Tooltip>
                    </div>
                  </Checkbox>
                </div>
              );
            })}
          </CheckboxGroup>
        </div>
      </div>
      <Divider type="vertical" style={{ height: "100%", margin: "0 15px" }} />
      <div
        style={{
          flex: 3,
          display: "flex",
          flexDirection: "column",
          height: "100%",
        }}
      >
        <div>
          <InitForm
            fields={bottomfields}
            submitData={(values, fn) => {}}
            onChange={(changedValues, allValues) => {
              for (let i in allValues) {
                tableFields["list"].value = [];
                tableFormRef.setFieldsValue({ list: [] });
                dispatch({
                  type: "changelastFields",
                  lastFields: { ...tableFields },
                });
              }
            }}
            actions={(form, submitBtn) => {
              return (
                <Button
                  style={{ marginLeft: 12 }}
                  type="primary"
                  onClick={() => {
                    dispatch({ type: "changeaddloading", addloading: true });
                    form
                      .validateFields()
                      .then((values) => {
                        for (let i in tableFields) {
                          tableFields[i].value = schedulingCheckedData;
                          tableFormRef.setFieldsValue({
                            [i]: schedulingCheckedData,
                          });
                        }
                        dispatch({
                          type: "changelastFields",
                          lastFields: { ...tableFields },
                        });
                        dispatch({
                          type: "changeaddloading",
                          addloading: false,
                        });
                      })
                      .catch((error) => {});
                  }}
                >{` 已选中${schedulingCheckedData.length}个车间计划`}</Button>
              );
            }}
            formRef={rightFormRef}
          ></InitForm>
        </div>
        <div
          style={{
            marginTop: 15,
            flex: 1,
            overflow: "hidden",
            overflowY: "auto",
          }}
        >
          {!addloading && (
            <InitForm
              fields={lastFields}
              submitData={(values, fn) => {}}
              onChange={(changedValues, allValues) => {}}
              actions={(form, submitBtn) => {
                return (
                  <Button
                    style={{ marginLeft: 12 }}
                    type="primary"
                    onClick={() => {
                      rightFormRef
                        .validateFields()
                        .then((values) => {
                          let newFields = form.getFieldsValue(),
                            rightForms = JSON.parse(JSON.stringify(values));
                          for (let i = 0; i < newFields.list.length; i++) {
                            if (!newFields.list[i].scheduledNum) {
                              return message.warning("排产数量需大于0！");
                            }
                          }
                          let params = newFields.list.map((it) => {
                            return {
                              productionLineId: rightForms.productionLineId,
                              productionDate: moment(
                                rightForms.productionDate
                              ).format("YYYY-MM-DD"),
                              shiftId: rightForms.shiftId,
                              scheduledNum: it.scheduledNum,
                              id: it.id,
                            };
                          });
                          run({
                            url: "/ngic-production/emPlanOrder/save",
                            params,
                          });
                        })
                        .catch((error) => {});
                    }}
                  >
                    生成派工单
                  </Button>
                );
              }}
              formRef={tableFormRef}
              submitting={loading || !schedulingVisible}
            ></InitForm>
          )}
        </div>
      </div>
    </div>
  );
};

export default Scheduling;
