import React, { useEffect, useReducer } from "react";
import {
  Input,
  Card,
  Tooltip,
  Button,
  Calendar,
  DatePicker,
  Select,
  Spin,
  Popconfirm,
  Switch,
} from "antd";
import styles from "./index.less";
import { doFetch } from "@/utils/doFetch";
import getPrem from "@/utils/getPrem"; //权限判断fn
import { useRequest } from "umi";
import moment from "moment";
import DrawInitForm from "@/components/DrawInitForm";
const initState = {
    vs: false,
    fields: {},
    iftype: {},
    scheduleData: [],
    year: moment().year(),
    month: moment().month() + 1,
    curitem: {},
    loadingData: false,
  },
  monthSelect = [],
  defaultFields = {
    isWeekday: {
      value: null,
      type: "radio",
      title: "修改工作日历",
      name: ["isWeekday"],
      required: true,
      options: [
        {
          label: "工作日",
          value: 1,
        },
        {
          label: "休息日",
          value: 0,
        },
      ],
    },
  };
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case "edit":
      newState = {
        ...state,
        vs: true,
        iftype: {
          title: "修改工作日历",
          val: type,
        },
        fields: { ...action.fields },
        curitem: { ...action.curitem },
      };
      break;
    case "changeData":
      newState = {
        ...state,
        scheduleData: action.scheduleData,
        loadingData: false,
      };
      break;
    case "changeLoading":
      newState = {
        ...state,
        loadingData: action.loadingData,
      };
      break;
    case "changeYear":
      newState = {
        ...state,
        year: action.year,
      };
      break;
    case "changeMonth":
      newState = {
        ...state,
        month: action.month,
      };
      break;
    case "close":
      newState = {
        ...state,
        vs: false,
        fields: {},
        iftype: {},
        curitem: {},
      };
      break;
  }

  return newState;
}
function getMonth() {
  for (let i = 1; i < 13; i++) {
    let obj = {
      value: i,
      label: i + "月",
    };
    monthSelect.push(obj);
  }
}
getMonth();
const Schedule = (props) => {
  const { checkedNode, reloadTree } = props;
  const { run, loading } = useRequest(doFetch, {
      manual: true,
      formatResult: (res) => res,
      onSuccess: (result, params) => {
        if (result.code == "0000") {
          dispatch({ type: "close" });
          reload();
          reloadTree && reloadTree();
        }
      },
    }),
    [state, dispatch] = useReducer(reducer, initState),
    { vs, fields, iftype, scheduleData, year, month, curitem } = state;
  useEffect(() => {
    if (checkedNode) {
      reload();
    } else {
      dispatch({ type: "changeMonth", month: moment().month() + 1 });
      dispatch({ type: "changeYear", year: moment().year() });
    }
  }, [checkedNode, year, month]);
  function reload() {
    dispatch({ type: "changeLoading", loadingData: true });
    doFetch({
      url: "/ngic-auth/sysWorkSchedule/queryMonth",
      params: { relationId: checkedNode.key, yearMonth: `${year}-${month}` },
    }).then((res) => {
      if (res.code == "0000") {
        let data = res?.data?.dataList ?? [];
        dispatch({ type: "changeData", scheduleData: data });
      }
    });
  }
  function getListData(value) {
    for (let i = 0; i < scheduleData.length; i++) {
      if (value.date() == scheduleData[i].day) {
        return scheduleData[i].isWeekday == 1 ? "工作日" : "休息日";
      }
    }
  }
  function dateCellRender(value) {
    const listData = getListData(value);
    let selectDate = value.format("YYYY-MM-DD"),
      selectDateObj = scheduleData.filter((it) => it.date == selectDate);
    return (
      <div
        onClick={(e) => {
          if (selectDateObj.length > 0) {
            for (let i in defaultFields) {
              defaultFields[i].value = selectDateObj[0][i];
            }
            dispatch({
              type: "edit",
              fields: defaultFields,
              curitem: selectDateObj[0],
            });
          }
        }}
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        {listData}
      </div>
    );
  }
  let saveData = (values, fn) => {
    let newfields = JSON.parse(JSON.stringify(values));
    //新增&修改
    let difrid = { id: curitem.id };
    run({
      url: "/ngic-auth/sysWorkSchedule/updateIsWeekday",
      params: { ...newfields, ...difrid },
    });
  };

  return (
    <div style={{ padding: 14 }}>
      {checkedNode ? (
        <>
          <Spin tip="数据加载中" spinning={loading}>
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>
                <Tooltip
                  title={
                    <div>
                      <span>所选组织结构：</span>
                      <span>
                        {checkedNode.title}
                        <span
                          style={{
                            color: `${checkedNode.isOpen ? "#1890ff" : "#ccc"}`,
                          }}
                        >
                          {checkedNode.isOpen ? "（已开启）" : "（未开启）"}
                        </span>
                      </span>
                    </div>
                  }
                >
                  <div style={{ maxWidth: 300 }} className="oneText">
                    <span>所选组织结构：</span>
                    <span>
                      {checkedNode.title}
                      <span
                        style={{
                          color: `${checkedNode.isOpen ? "#1890ff" : "#ccc"}`,
                        }}
                      >
                        {checkedNode.isOpen ? "（已开启）" : "（未开启）"}
                      </span>
                    </span>
                  </div>
                </Tooltip>
              </div>
              {checkedNode.type != 1 && (
                <div style={{ marginLeft: 15 }}>
                  <Popconfirm
                    title="是否开启或关闭?"
                    onConfirm={() => {
                      run({
                        url: "/ngic-auth/sysDepartmentWorkSchedule/updateIsOpen",
                        params: {
                          relationId: checkedNode.key,
                          isOpen: checkedNode.isOpen == 1 ? 0 : 1,
                        },
                      });
                    }}
                    onCancel={() => {}}
                    okText="确定"
                    cancelText="取消"
                    disabled={!getPrem("equipmentSupplier_updatestatus", "ifs")}
                  >
                    <Switch
                      checked={checkedNode.isOpen == 1 ? true : false}
                      checkedChildren="开启"
                      unCheckedChildren="关闭"
                      defaultChecked={false}
                    />
                  </Popconfirm>
                  <Button
                    style={{ marginLeft: 15 }}
                    disabled={checkedNode.isOpen != 1}
                    type="primary"
                    onClick={() => {
                      run({
                        url: "/ngic-auth/sysDepartmentWorkSchedule/copyParent",
                        params: {
                          relationId: checkedNode.key,
                          parentRelationId: checkedNode.parentKey,
                        },
                      });
                    }}
                  >
                    引用上层
                  </Button>
                </div>
              )}
            </div>

            <Calendar
              dateCellRender={dateCellRender}
              headerRender={({ value, type, onChange, onTypeChange }) => {
                return (
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "flex-end",
                      marginBottom: 20,
                    }}
                  >
                    <DatePicker
                      value={moment(String(year))}
                      onChange={(date, dateString) => {
                        dispatch({ type: "changeYear", year: dateString });
                        let year = value.clone().year(dateString);
                        onChange(year);
                      }}
                      picker="year"
                    />
                    <Select
                      value={month}
                      onChange={(selectedMonth, val, e) => {
                        dispatch({ type: "changeMonth", month: selectedMonth });
                        const newValue = value.clone();
                        newValue.month(parseInt(selectedMonth - 1, 10));
                        onChange(newValue);
                      }}
                      style={{ width: 120, marginLeft: 15 }}
                    >
                      {monthSelect.map((it) => {
                        return (
                          <Select.Option
                            className="month-item"
                            key={it.value}
                            value={it.value}
                          >
                            {it.label}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </div>
                );
              }}
              disabledDate={(date) => {
                if (checkedNode.type == 1) {
                  if (date.endOf("d").valueOf() < moment().valueOf()) {
                    return true;
                  }
                  return false;
                } else {
                  if (checkedNode.isOpen == 1) {
                    if (date.endOf("d").valueOf() < moment().valueOf()) {
                      return true;
                    }
                    return false;
                  } else {
                    return true;
                  }
                }
              }}
            />
          </Spin>
          <DrawInitForm
            title={iftype.title}
            visible={vs}
            onClose={() => dispatch({ type: "close" })}
            footer={false}
            destroyOnClose={true}
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={loading || !vs}
            width={"60%"}
          >
            <div style={{ marginBottom: 15 }}>
              <Tooltip
                title={
                  <div>
                    <span>所选组织结构：</span>
                    <span>
                      {checkedNode.title}
                      <span
                        style={{
                          color: `${checkedNode.isOpen ? "#1890ff" : "#ccc"}`,
                        }}
                      >
                        {checkedNode.isOpen ? "（已开启）" : "（未开启）"}
                      </span>
                    </span>
                  </div>
                }
              >
                <div
                  style={{ width: "100%", marginBottom: 10 }}
                  className="oneText"
                >
                  <span>所选组织结构：</span>
                  <span>
                    {checkedNode.title}
                    <span
                      style={{
                        color: `${checkedNode.isOpen ? "#1890ff" : "#ccc"}`,
                      }}
                    >
                      {checkedNode.isOpen ? "（已开启）" : "（未开启）"}
                    </span>
                  </span>
                </div>
              </Tooltip>
              <Tooltip
                title={
                  <div>
                    <span>所选日期：</span>
                    <span>{curitem.date}</span>
                  </div>
                }
              >
                <div style={{ width: "100%" }} className="oneText">
                  <span>所选日期：</span>
                  <span>{curitem.date}</span>
                </div>
              </Tooltip>
            </div>
          </DrawInitForm>
        </>
      ) : (
        <></>
      )}
    </div>
  );
};
export default Schedule;
