import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import { message, Popconfirm, Switch } from 'antd';
import DrawerPro from '@/components/DrawerPro';
import DetailPro from '@/components/DetailPro';
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 { doFetch } from '@/utils/doFetch';
import dayjs from 'dayjs';
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 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 editDate = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '调整日期',
              val: 'detailaddon',
              id: row?.id,
            }));
          },
        }}
      >
        调整日期
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };
  const close = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否关单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({ url: '/check/umEquipmentCheckPlan/shut', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        关单
      </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: 'checkEnable',
            key: 'checkEnable',
            hideInForm: true,
            hideInSearch: true,
            valueType: 'switch',
            render: (text, row, _, action) => {
              //"1停用  2启用 *"
              return row.checkEnable == 1 ? (
                <Popconfirm
                  title="是否开启或停用?"
                  onConfirm={async () => {
                    if (row.checkEnable == 1) {
                      await runAsync({
                        url: '/check/umEquipmentCheckPlan/enable',
                        params: { id: row.id, checkEnable: 2 },
                      });
                    }
                  }}
                  okText="确定"
                  cancelText="取消"
                  disabled={!(row.status == 1 || (row.status == 2 && row.checkLoop == 2))}
                >
                  <Switch
                    checked={row.checkEnable == 1 ? true : false}
                    checkedChildren="开启"
                    unCheckedChildren="停用"
                    defaultChecked={false}
                    disabled={!(row.status == 1 || (row.status == 2 && row.checkLoop == 2))}
                  />
                </Popconfirm>
              ) : (
                <Switch
                  checked={row.checkEnable == 1 ? true : false}
                  checkedChildren="开启"
                  unCheckedChildren="停用"
                  defaultChecked={false}
                  disabled={!(row.status == 1 || (row.status == 2 && row.checkLoop == 2))}
                  onChange={(checked) => {
                    if (checked) {
                      setdrawer((s) => ({
                        ...s,
                        open: true,
                        item: row,
                        title: '启用点检计划',
                        val: 'detailaddon',
                        type: 'delay',
                        id: row?.id,
                      }));
                    }
                  }}
                />
              );
            },
            hideInDescriptions: true,
          },
          {
            title: '操作',
            valueType: 'option',
            width: 150,
            render: (text, row, _, action) => [
              (row.status == 1 || (row.status == 2 && row.checkLoop == 2)) &&
                editDate(text, row, _, action),
              row.status == 2 && close(text, row, _, action),
              defpath?.enabledelete && row.status == 1 && remove(text, row, _, action),
            ],
          },
        ])
      : defcolumn;
  }, [activeTabKey]);

  const editDateColumns = useMemo(() => {
    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: 'checkNo',
        key: 'checkNo',
        hideInForm: true,
      },
      {
        title: '设备编号',
        dataIndex: 'equipmentNo',
        key: 'equipmentNo',
        hideInForm: true,
      },
      {
        title: '设备名称',
        dataIndex: 'equipmentName',
        key: 'equipmentName',
        hideInForm: true,
      },
      {
        title: '点检类型',
        dataIndex: 'checkTypeName',
        key: 'checkType',
        hideInForm: true,
      },
      {
        title: '下次点检日期',
        dataIndex: 'planCheckDate',
        key: 'planCheckDateList',
        hideInForm: true,
      },
      {
        title: '计划类型',
        dataIndex: 'checkLoopName',
        key: 'checkLoop',
        hideInForm: true,
      },
      {
        title: '调整信息',
        valueType: 'split',
        hideInForm: true,
      },
      {
        title: '下次点检日期',
        dataIndex: 'planCheckDate',
        key: 'planCheckDate',
        formItemProps: {
          rules: [
            {
              required: true,
              message: '此项为必填项',
            },
          ],
        },
        fieldProps: {
          disabledDate,
        },
        valueType: 'date',
        hideInSearch: true,
        hideInDescriptions: true,
      },
      {
        title: '周期(天)',
        dataIndex: 'checkCycle',
        key: 'checkCycle',
        hideInSearch: true,
        hideInDescriptions: true,
        valueType: 'digit',
        hideInForm: drawer?.item?.checkLoop == 2 ? false : true,
        precision: 0,
      },
    ];
  }, [drawer?.item]);

  const detailsColumns = useMemo(() => {
    const columnsc = [
      {
        title: '点检项目',
        dataIndex: 'checkItem',
        key: 'checkItem',
        hideInForm: true,
      },
      {
        title: '部位',
        dataIndex: 'checkPosition',
        key: 'checkPosition',
        hideInForm: true,
      },
      {
        title: '点检方法',
        dataIndex: 'checkWay',
        key: 'checkWay',
        hideInForm: true,
      },
    ];
    if (drawer?.val == 'detail') {
      return [
        {
          title: '计划信息',
          valueType: 'split',
        },
        {
          title: '点检计划单号',
          dataIndex: 'checkNo',
          key: 'checkNo',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '启用/停用',
          dataIndex: 'checkEnableName',
          key: 'checkEnableName',
        },
        {
          title: '下次点检日期',
          dataIndex: 'planCheckDate',
          key: 'planCheckDate',
          span: activeTabKey == 1 ? 2 : 1,
        },
        {
          title: '关单日期',
          dataIndex: 'endDate',
          key: 'endDate',
          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: 'checkTypeName',
          key: 'checkTypeName',
        },
        {
          title: '计划类型',
          dataIndex: 'checkLoopName',
          key: 'checkLoopName',
        },
        {
          title: '周期(天)',
          dataIndex: 'checkCycle',
          key: 'checkCycle',
          span: activeTabKey == 1 ? 2 : 2,
        },
        {
          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?.itemList}
              />
            );
          },
        },
        {
          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 pathconfig = useMemo(() => {
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defpath;
  }, [activeTabKey]);
  const waitTime = (time) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };
  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}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            type: 'primary',
            disabled: false,
            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}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={async (vals) => {
          let params = JSON.parse(JSON.stringify(vals));
          params.paramList = params?.paramList?.map((it) => {
            return {
              equipmentId: it.id,
              checkPlanDate: it.checkPlanDate,
            };
          });
          let flag = params.paramList?.some((it) => !it.checkPlanDate);
          if (flag) {
            message.warning('下次点检日期必填!');
            return;
          }
          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={{ checkCycle: drawer?.item?.checkCycle }}
          onFinish={async (vals) => {
            await runAsync({
              url:
                drawer?.type == 'delay'
                  ? '/check/umEquipmentCheckPlan/enable'
                  : '/check/umEquipmentCheckPlan/adjustDate',
              params: { ...vals, id: drawer?.item?.id, checkEnable: 1 },
            });
          }}
        />
      </DrawerPro>
    </div>
  );
}

export default Plan;