import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import { Radio, InputNumber, Input } 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 { doFetch } from '@/utils/doFetch';

function Task(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
      open: false,
    }),
    [activeTabKey, setactiveTabKey] = useState('1'),
    [detailData, cd] = useState({});

  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 edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '编辑',
              val: 'edit',
            }));
          },
        }}
      >
        编辑
      </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 order = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否接单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({ url: '/check/umEquipmentCheckTask/meet', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
        }}
      >
        接单
      </PremButton>
    );
  };
  const close = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否关单?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            await runAsync({ url: '/check/umEquipmentCheckTask/shut', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        关单
      </PremButton>
    );
  };
  const finish = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            doFetch({
              url: '/check/umEquipmentCheckTask/queryDetails',
              params: { id: row.id },
            }).then((res) => {
              if (res.code == '0000') {
                setdrawer((s) => ({
                  ...s,
                  open: true,
                  item: {
                    ...res.data?.basics,
                    ...res.data?.meet,
                    id: row.id,
                  },
                  title: '点检工单',
                  val: 'detailaddon',
                }));
              }
            });
          },
        }}
      >
        完成点检
      </PremButton>
    );
  };

  const detailaddonColumns = useMemo(() => {
    if (activeTabKey == 1) {
      const columnsc = [
        {
          title: '点检项目',
          dataIndex: 'checkItem',
          key: 'checkItem',
          hideInForm: true,
        },
        {
          title: '部位',
          dataIndex: 'checkPosition',
          key: 'checkPosition',
          hideInForm: true,
        },
        {
          title: '点检方法',
          dataIndex: 'checkWay',
          key: 'checkWay',
          hideInForm: true,
        },
        {
          title: '结果',
          dataIndex: 'result',
          key: 'result',
          hideInForm: true,
          render: (text, row, _, action) => {
            return row.judgeType == 1 ? (
              <Radio.Group
                onChange={(e) => {
                  row.result = e.target.value;
                }}
              >
                <Radio value={1}>正常</Radio>
                <Radio value={2}>异常</Radio>
              </Radio.Group>
            ) : (
              <InputNumber
                onChange={(value) => {
                  row.result = value;
                }}
              />
            );
          },
        },
        {
          title: '下限值',
          dataIndex: 'lowerLimit',
          key: 'lowerLimit',
          hideInForm: true,
        },
        {
          title: '上限值',
          dataIndex: 'upperLimit',
          key: 'upperLimit',
          hideInForm: true,
        },
        {
          title: '备注',
          dataIndex: 'remark',
          key: 'remark',
          hideInForm: true,
          render: (text, row, _, action) => {
            return (
              <Input
                onChange={(e) => {
                  row.remark = e.target.value;
                }}
              />
            );
          },
        },
      ];
      return [
        {
          title: '工单信息',
          valueType: 'split',
        },
        {
          title: '点检单号',
          dataIndex: 'taskNo',
          key: 'taskNo',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '工单状态',
          dataIndex: 'statusName',
          key: 'statusName',
        },
        {
          title: '点检计划单号',
          dataIndex: 'planNo',
          key: 'planNo',
        },
        {
          title: '设备编号',
          dataIndex: 'equipmentNo',
          key: 'equipmentNo',
        },
        {
          title: '设备名称',
          dataIndex: 'equipmentName',
          key: 'equipmentName',
        },
        {
          title: '设备型号',
          dataIndex: 'equipmentModelName',
          key: 'equipmentModelName',
        },
        {
          title: '点检类型',
          dataIndex: 'checkTypeName',
          key: 'checkTypeName',
        },
        {
          title: '点检截止日期',
          dataIndex: 'checkCloseDate',
          key: 'checkCloseDate',
        },
        {
          title: '接单时间',
          dataIndex: 'checkStartTime',
          key: 'checkStartTime',
        },
        {
          title: '完成点检',
          valueType: 'split',
        },
        {
          title: '点检方法',
          dataIndex: 'itemList',
          key: 'itemList',
          columns,
          span: 3,
          render: (text, row, _, action) => {
            return (
              <AutoTables
                columns={columnsc?.map((it) => ({
                  ...it,
                  hideInSearch: true,
                }))}
                dataSource={drawer?.item?.item ?? []}
              />
            );
          },
        },
      ];
    }
  }, [drawer?.item, activeTabKey]);

  const detailColumns = useMemo(() => {
    if (drawer?.val == 'detail') {
      const columnsc = [
        {
          title: '点检项目',
          dataIndex: 'checkItem',
          key: 'checkItem',
          hideInForm: true,
        },
        {
          title: '部位',
          dataIndex: 'checkPosition',
          key: 'checkPosition',
          hideInForm: true,
        },
        {
          title: '点检方法',
          dataIndex: 'checkWay',
          key: 'checkWay',
          hideInForm: true,
        },
      ];
      const allObj = {
          task: [
            {
              title: '工单信息',
              valueType: 'split',
            },
            {
              title: '点检单号',
              dataIndex: 'taskNo',
              key: 'taskNo',
            },
            {
              title: '创建时间',
              dataIndex: 'createTime',
              key: 'createTime',
            },
            {
              title: '工单状态',
              dataIndex: 'statusName',
              key: 'statusName',
            },
            {
              title: '点检计划单号',
              dataIndex: 'planNo',
              key: 'planNo',
              span: activeTabKey == 3 ? 1 : 3,
            },
            {
              title: '关单时间',
              dataIndex: 'endTime',
              key: 'endTime',
              hideInDescriptions: activeTabKey == 3 ? false : true,
            },
          ],
          basics: [
            {
              title: '基础信息',
              valueType: 'split',
            },
            {
              title: '设备编号',
              dataIndex: 'equipmentNo',
              key: 'equipmentNo',
            },
            {
              title: '设备名称',
              dataIndex: 'equipmentName',
              key: 'equipmentName',
            },
            {
              title: '设备型号',
              dataIndex: 'equipmentModelName',
              key: 'equipmentModelName',
            },
            {
              title: '点检类型',
              dataIndex: 'checkTypeName',
              key: 'checkTypeName',
            },
            {
              title: '点检截止日期',
              dataIndex: 'checkCloseDate',
              key: 'checkCloseDate',
              span: 2,
            },
            {
              title: '点检项目',
              dataIndex: 'itemList',
              key: 'itemList',
              columns,
              span: 3,
              render: (text, row, _, action) => {
                return (
                  <AutoTables
                    columns={columnsc?.map((it) => ({
                      ...it,
                      hideInSearch: true,
                    }))}
                    dataSource={drawer?.item?.basics?.item ?? []}
                  />
                );
              },
              hideInDescriptions: drawer?.item?.task?.status != 4 ? false : true,
            },
          ],
          meet: [
            {
              title: '接单信息',
              valueType: 'split',
            },
            {
              title: '点检人员',
              dataIndex: 'checkUserName',
              key: 'checkUserName',
            },
            {
              title: '接单时间',
              dataIndex: 'checkStartTime',
              key: 'checkStartTime',
              span: 2,
            },
          ],
          delay: [
            {
              title: '完成点检',
              valueType: 'split',
            },
            {
              title: '完成点检时间',
              dataIndex: 'checkEndTime',
              key: 'checkEndTime',
              span: 3,
            },
            {
              title: '点检项目',
              dataIndex: 'itemList',
              key: 'itemList',
              columns,
              span: 3,
              render: (text, row, _, action) => {
                return (
                  <AutoTables
                    columns={columnsc
                      .concat([
                        {
                          title: '结果',
                          dataIndex: 'result',
                          key: 'result',
                          hideInForm: true,
                          render: (text, row, _, action) => {
                            return (
                              <span>
                                {row.judgeType == 1
                                  ? row.result == 1
                                    ? '正常'
                                    : '异常'
                                  : row.result}
                              </span>
                            );
                          },
                        },
                        {
                          title: '下限值',
                          dataIndex: 'lowerLimit',
                          key: 'lowerLimit',
                          hideInForm: true,
                        },
                        {
                          title: '上限值',
                          dataIndex: 'upperLimit',
                          key: 'upperLimit',
                          hideInForm: true,
                        },
                        {
                          title: '备注',
                          dataIndex: 'remark',
                          key: 'remark',
                          hideInForm: true,
                        },
                      ])
                      ?.map((it) => ({
                        ...it,
                        hideInSearch: true,
                      }))}
                    dataSource={drawer?.item?.delay?.itemlist ?? []}
                  />
                );
              },
              hideInDescriptions: drawer?.item?.task?.status == 4 ? false : true,
            },
          ],
          shut: [
            {
              title: '关单信息',
              valueType: 'split',
            },
            {
              title: '关单人员',
              dataIndex: 'shutUserName',
              key: 'shutUserName',
            },
            {
              title: '强制关单时间',
              dataIndex: 'shutTime',
              key: 'shutTime',
            },
          ],
        },
        newObject = {};
      let data = JSON.parse(JSON.stringify(drawer?.item)),
        objectData = {};
      let dataKeys = Object.keys(data),
        allObjKeys = Object.keys(allObj),
        newObjKes = allObjKeys.filter((it) => dataKeys.indexOf(it) > -1);
      newObjKes.map((it) => {
        newObject[it] = allObj[it];
      });
      let newColumns = [];
      for (let i in newObject) {
        newColumns = [...newColumns, ...newObject[i]];
      }
      for (let i in data) {
        objectData = Object.assign(objectData, data[i]);
      }
      cd(objectData);
      return newColumns;
    }
  }, [drawer?.item, activeTabKey]);

  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: '操作',
          valueType: 'option',
          width: 150,
          render: (text, row, _, action) => [
            row.status == 1 && order(text, row, _, action),
            row.status == 1 && close(text, row, _, action),
            row.status == 2 && finish(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}
        nocardtab={true}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            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' ? detailaddonColumns : detailColumns}
        detailpath={pathconfig?.detail || null}
        detailData={drawer.val == 'detail' ? detailData : drawer?.item}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={(vals) => {
          if (drawer?.val == 'add') {
            run({ url: pathconfig?.add || '/add', params: { ...vals } });
          } else if (drawer?.val == 'edit') {
            run({ url: pathconfig?.edit || '/edit', params: { ...vals, id: drawer?.item?.id } });
          }
        }}
      >
        <div>
          <PremButton
            btn={{
              type: 'primary',
              loading,
              onClick: () => {
                let itemList = drawer?.item?.item?.map((it) => {
                  if (it.judgeType == 1) {
                    return {
                      id: it.id,
                      remark: it.remark,
                      judgeResultQualitative: it.result,
                    };
                  } else {
                    return {
                      id: it.id,
                      remark: it.remark,
                      judgeResultRation: it.result,
                    };
                  }
                });
                run({
                  url: '/check/umEquipmentCheckTask/complele',
                  params: { id: drawer?.item?.id, itemList },
                });
              },
            }}
          >
            提交
          </PremButton>
        </div>
      </DrawerPro>
    </div>
  );
}

export default Task;
