/* 保养计划
 * @Author: Li Hanlin
 * @Date: 2023-01-16 15:35:00
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-02-16 17:45:48
 */

import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import { Switch, Popconfirm, message } from 'antd';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import AutoTables from '@/components/AutoTable/mtable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { useRequest } from 'ahooks';
import dayjs from 'dayjs';
import { doFetch } from '@/utils/doFetch';
import InitForm from '@/components/InitForm';
function Plan(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
      open: false,
    }),
    [activeTabKey, setactiveTabKey] = useState('1');

  const { run, loading, runAsync } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  const editDateColumns = useMemo(() => {
    const disabledDateOfDay = (current) => {
      // Can not select days before today and today
      return current && current < dayjs().endOf('day');
    };
    const disabledDateOfMonth = (current) => {
      // Can not select days before today and today
      return current && current < dayjs().startOf('month');
    };
    const disabledDate = (current) => {
      if (drawer?.item?.status == 1) {
        return current && current < dayjs().endOf('day');
      } else {
        if (
          dayjs(drawer?.item?.planCheckDate).endOf('day').valueOf() >=
          dayjs().endOf('day').valueOf()
        ) {
          return current && current <= dayjs(drawer?.item?.planCheckDate).endOf('day');
        } else {
          return current && current < dayjs().endOf('day');
        }
      }
    };
    return [
      {
        title: '计划信息',
        valueType: 'split',
        hideInForm: true,
      },
      {
        title: '保养计划单号',
        dataIndex: 'maintainNo',
        key: 'maintainNo',
        hideInForm: true,
      },
      {
        title: '设备编号',
        dataIndex: 'equipmentNo',
        key: 'equipmentNo',
        hideInForm: true,
      },
      {
        title: '设备名称',
        dataIndex: 'equipmentName',
        key: 'equipmentName',
        hideInForm: true,
      },
      {
        title: '保养类型',
        dataIndex: 'maintainTypeName',
        key: 'maintainTypeName',
        hideInForm: true,
      },
      {
        title: '下次保养日期',
        dataIndex: 'nextMaintainDate',
        key: 'nextMaintainDate',
        hideInForm: true,
      },
      {
        title: '调整信息',
        valueType: 'split',
        hideInForm: true,
      },
      {
        title: '保养频次',
        hideInDescriptions: true,
        dataIndex: 'maintainFrequencyName',
        key: 'maintainFrequency',
        fieldProps: {
          disabled: true,
        },
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
        valueType: 'select',
        mode: 'radio',
        options: [
          {
            label: '周',
            value: 0,
          },
          {
            label: '月度',
            value: 1,
          },
          {
            label: '季度',
            value: 2,
          },
          {
            label: '半年',
            value: 3,
          },
          {
            label: '年度',
            value: 4,
          },
        ],
      },
      {
        title: '计划类型',
        dataIndex: 'isCycle',
        hideInDescriptions: true,
        key: 'isCycle',
        fieldProps: {
          disabled: true,
        },
        valueType: 'select',
        mode: 'radio',
        options: [
          {
            label: '单次',
            value: 1,
          },
          {
            label: '周期',
            value: 2,
          },
        ],
      },
      {
        title: '下次保养日期',
        dataIndex: 'nextMaintainDate',
        key: 'nextMaintainDate',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
        fieldProps: {
          disabledDate: disabledDateOfDay,
        },
        valueType: 'date',
        hideInSearch: true,
        hideInDescriptions: true,
        hideInForm: {
          maintainFrequency: {
            reverse: [0],
          },
        },
      },
      {
        title: '下次保养日期',
        dataIndex: 'nextMaintainDate',
        key: 'nextMaintainDate',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
        fieldProps: {
          disabledDate: disabledDateOfMonth,
        },
        valueType: 'dateMonth',
        hideInForm: {
          maintainFrequency: [0],
        },
        hideInSearch: true,
        hideInDescriptions: true,
      },
    ];
  }, [drawer?.item]);

  const detail = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          type: 'link',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: '详细信息',
            }));
          },
        }}
      >
        详情
      </PremButton>
    );
  };

  const detailsColumns = useMemo(() => {
    const columnsc = [
      {
        title: '保养项目',
        dataIndex: 'maintainItemName',
        key: 'maintainItemName',
        hideInForm: true,
      },
      {
        title: '部位',
        dataIndex: 'maintainPosition',
        key: 'maintainPosition',
        hideInForm: true,
      },
      {
        title: '保养方法',
        dataIndex: 'maintainWay',
        key: 'maintainWay',
        hideInForm: true,
      },
    ];
    if (drawer?.val == 'detail') {
      return [
        {
          title: '计划信息',
          valueType: 'split',
        },
        {
          title: '保养计划单号',
          dataIndex: 'maintainNo',
          key: 'maintainNo',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '状态',
          dataIndex: 'maintainStatus',
          key: 'maintainStatus',
          render: (_, row) => {
            return row?.maintainStatus == 1 ? '未开始' : '执行中';
          },
        },
        {
          title: '启用/停用',
          dataIndex: 'isStopStatusName',
          key: 'isStopStatusName',
        },
        {
          title: '下次保养日期',
          dataIndex: 'nextMaintainDate',
          key: 'nextMaintainDate',
          span: activeTabKey == 1 ? 2 : 1,
        },
        {
          title: '关单日期',
          dataIndex: 'customsTime',
          key: 'customsTime',
          hideInDescriptions: activeTabKey == 1 ? true : false,
        },
        {
          title: '基本信息',
          valueType: 'split',
        },
        {
          title: '设备编号',
          dataIndex: 'equipmentNo',
          key: 'equipmentNo',
        },
        {
          title: '设备名称',
          dataIndex: 'equipmentName',
          key: 'equipmentName',
        },
        {
          title: '设备型号',
          dataIndex: 'equipmentModelName',
          key: 'equipmentModelName',
        },
        {
          title: '工厂名称',
          dataIndex: 'factoryName',
          key: 'factoryName',
        },
        {
          title: '车间名称',
          dataIndex: 'shopName',
          key: 'shopName',
        },
        {
          title: '保养类型',
          dataIndex: 'maintainTypeName',
          key: 'maintainTypeName',
        },
        {
          title: '保养频次',
          dataIndex: 'maintainFrequencyName',
          key: 'maintainFrequencyName',
        },
        {
          title: '计划类型',
          dataIndex: 'isCycle',
          key: 'isCycle',
          span: activeTabKey == 1 ? 3 : 3,
          render: (_, row) => {
            return row?.isCycle == 1 ? '单次' : '周期';
          },
        },
        {
          title: '保养项目',
          valueType: 'split',
        },
        {
          dataIndex: 'itemList',
          key: 'itemList',
          valueType: 'formList',
          colProps: {
            span: 24,
          },
          columns,
          span: 24,
          render: (text, row) => {
            return (
              <AutoTables
                columns={columnsc?.map((it) => ({
                  ...it,
                  hideInSearch: true,
                }))}
                dataSource={row?.maintainItemList}
              />
            );
          },
        },
        {
          title: '关单信息',
          valueType: 'split',
          hideInDescriptions: drawer?.item?.status != 3 ? true : false,
        },
        {
          title: '关单人员',
          dataIndex: 'shutUserName',
          key: 'shutUserName',
          hideInDescriptions: drawer?.item?.status != 3 ? true : false,
        },
        {
          title: '强制关单时间',
          dataIndex: 'shutTime',
          key: 'shutTime',
          hideInDescriptions: drawer?.item?.status != 3 ? true : false,
        },
      ];
    }
  }, [drawer?.val, activeTabKey, drawer?.item?.id]);

  const close = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否关单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({
              url: '/maintain/umMaintainPlan/customsDeclaration',
              params: { id: row?.id },
            });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        关单
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => {
            run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const editDate = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '调整日期',
              val: 'detailaddon',
              id: row?.id,
              from: 'tz',
            }));
          },
        }}
      >
        调整日期
      </PremButton>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.columns;
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return activeTabKey == 1
      ? defcolumn.concat([
          {
            title: '启用/停用',
            dataIndex: 'isStopStatus',
            key: 'isStopStatus',
            hideInForm: true,
            hideInSearch: true,
            valueType: 'switch',
            render: (text, row, _, action) => {
              //"1停用  2启用 *"
              return row.isStopStatus == 1 ? (
                <Popconfirm
                  title="是否开启或停用?"
                  onConfirm={async () => {
                    if (row.isStopStatus == 1) {
                      await runAsync({
                        url: '/maintain/umMaintainPlan/enableDeactivate',
                        params: { id: row.id, isStopFlag: 2 },
                      });
                    }
                  }}
                  okText="确定"
                  cancelText="取消"
                  disabled={
                    !(row.maintainStatus == 1 || (row.maintainStatus == 2 && row.isCycle == 2))
                  }
                >
                  <Switch
                    checked={row.isStopStatus == 1 ? true : false}
                    checkedChildren="开启"
                    unCheckedChildren="停用"
                    defaultChecked={false}
                    disabled={
                      !(row.maintainStatus == 1 || (row.maintainStatus == 2 && row.isCycle == 2))
                    }
                  />
                </Popconfirm>
              ) : (
                <Switch
                  checked={row.isStopStatus == 1 ? true : false}
                  checkedChildren="开启"
                  unCheckedChildren="停用"
                  defaultChecked={false}
                  disabled={
                    !(row.maintainStatus == 1 || (row.maintainStatus == 2 && row.isCycle == 2))
                  }
                  onChange={(checked) => {
                    if (checked) {
                      setdrawer((s) => ({
                        ...s,
                        open: true,
                        item: row,
                        title: '启用保养计划',
                        val: 'detailaddon',
                        id: row?.id,
                        from: 'tq',
                      }));
                    }
                  }}
                />
              );
            },
            hideInDescriptions: true,
          },
          {
            title: '操作',
            valueType: 'option',
            width: 150,
            render: (text, row, _, action) => [
              (row.maintainStatus == 1 || (row.maintainStatus == 2 && row.isCycle == 2)) &&
                editDate(text, row, _, action),
              row.maintainStatus == 2 && close(text, row, _, action),
              defpath?.enabledelete && row.maintainStatus == 1 && remove(text, row, _, action),
            ],
          },
        ])
      : defcolumn;
  }, [activeTabKey]);

  const pathconfig = useMemo(() => {
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defpath;
  }, [activeTabKey]);

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">保养计划</h3>}
        columns={columns}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        actionRef={actionRef}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: null,
                title: '新增',
                val: 'add',
              }));
            },
          },
        }}
        tabList={getcolumns()}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          setactiveTabKey(key);
        }}
      />

      <DrawerPro
        fields={
          drawer?.val == 'detailaddon'
            ? editDateColumns
            : drawer?.val == 'detail'
            ? detailsColumns
            : columns
        }
        detailpath={pathconfig?.detail || null}
        onValuesChange={(changedValues, allValues) => {
          if (Object.keys(changedValues)[0] == 'maintainFrequency') {
            formRef?.current?.setFieldsValue({
              paramList: [],
            });
          }
        }}
        // detailData={drawer?.item}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={async (vals) => {
          let flag = vals.paramList?.some((it) => !it.nextMaintainDate);
          if (flag) {
            message.warning('下次保养日期必填！');
            return;
          }
          let params = JSON.parse(JSON.stringify(vals));
          params.equipmentList = vals?.paramList?.map((it) => {
            return {
              id: it.id,
              nextMaintainDate: it.nextMaintainDate,
            };
          });
          delete params.paramList;

          if (drawer?.val == 'add') {
            await runAsync({ url: pathconfig?.add || '/add', params: { ...params } });
          } else if (drawer?.val == 'edit') {
            await runAsync({
              url: pathconfig?.edit || '/edit',
              params: { ...params, id: drawer?.item?.id },
            });
          }
        }}
      >
        <InitForm
          fields={editDateColumns}
          defaultFormValue={{
            isCycle: drawer?.item?.isCycle,
            maintainFrequency: drawer?.item?.maintainFrequency,
          }}
          onFinish={async (vals) => {
            delete vals.isCycle;
            delete vals.maintainFrequency;
            if (drawer?.from == 'tq') {
              vals.isStopFlag = 1;
              await runAsync({
                url: '/maintain/umMaintainPlan/enableDeactivate',
                params: { ...vals, id: drawer?.item?.id },
              });
            } else {
              await runAsync({
                url: '/maintain/umMaintainPlan/adjustDate',
                params: { ...vals, id: drawer?.item?.id },
              });
            }
          }}
        />
      </DrawerPro>
    </div>
  );
}

export default Plan;
