/* 设备台账
 * @Author: Li Hanlin
 * @Date: 2022-11-10 09:39:56
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2022-11-17 17:25:54
 */

import * as React from 'react';
import { useState, useMemo, useRef, useEffect } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch } from '@/utils/doFetch';
import { message, Dropdown, Menu, Layout, Button, Space } from 'antd';
import TreeRender from '@/components/TreeRender';
import { ProDescriptions } from '@ant-design/pro-components';

const { Sider, Content } = Layout;
function Model(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });

  const urlParams = {
    save: '/asset/equipment/save',
    remove: '/asset/equipment/deleteById',
    list: '/asset/equipment/queryList',
    detail: '/asset/equipment/detail',
  };

  const urlParams_childEquipment = {
    list: '/asset/equipment/children/queryList',
    checked: '/asset/equipment/children/selected/queryList',
    save: '/asset/equipmentChildren/save',
  };

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

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              title: '编辑',
              val: 'edit',
              detailpath: urlParams.detail,
              params: { id: row.id },
              onFinish: async (vals) => {
                console.log(1);
                let params = {
                  ...vals,
                  id: row.id,
                };
                let res = await doFetch({
                  url: urlParams.save,
                  params,
                });
                if (res.code === '0000') {
                  message.success('新增成功！');
                  setDrawer((s) => ({
                    ...s,
                    visible: false,
                  }));
                  actionRef.current.reload();
                }
              },
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除该设备?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { id: row.id } });
            if (res.code === '0000') {
              message.success('删除成功！');
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  const more = (text, row, _, action) => {
    const menu = (
      <Menu
        items={[
          {
            label: (
              <a
                onClick={() => {
                  setDrawer((s) => ({
                    ...s,
                    visible: true,
                    type: 'editChildEquipment',
                    item: {
                      id: row.id,
                    },
                    title: '详情',
                    val: 'only',
                    title: '编辑子设备',
                    onFinish: async (vals) => {
                      console.log(1);
                      let params = {
                        ...vals,
                        id: row.id,
                      };
                      let res = await doFetch({
                        url: urlParams.save,
                        params,
                      });
                      if (res.code === '0000') {
                        message.success('新增成功！');
                        setDrawer((s) => ({
                          ...s,
                          visible: false,
                        }));
                        actionRef.current.reload();
                      }
                    },
                  }));
                }}
              >
                编辑子设备
              </a>
            ),
            key: '0',
          },
          {
            label: <a>履历登记</a>,
            key: '1',
          },
          {
            label: <a>关联备件(暂缓)</a>,
            key: '2',
          },
          {
            label: <a>寿命件台账(暂缓)</a>,
            key: '3',
          },
        ]}
      />
    );
    return (
      <Dropdown
        overlay={menu}
        trigger={['click']}
        arrow={true}
        getPopupContainer={() => document.getElementsByClassName('ant-table-content')[0]}
      >
        <Button size="small">更多</Button>
      </Dropdown>
    );
  };

  const EditChildEquipment = () => {
    const [selectArr, setSelectArr] = useState([]);
    useEffect(() => {
      const fun = async () => {
        const result = await doFetch({
          url: '/asset/equipment/children/selected/queryList',
          params: { id: drawer?.item?.id },
        });
        // console.log(result);
        if (!result?.data?.dataList.length == 0) {
          setSelectArr(result?.data?.dataList.map((it) => it.id));
        }
      };
      fun();
    }, []);
    const columns = [
      {
        title: '设备编号',
        dataIndex: 'equipmentNo',
        key: 'equipmentNo',
        align: 'center',
        width: 120,
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
      {
        title: '设备名称',
        dataIndex: 'equipmentName',
        align: 'center',
        width: 120,
        key: 'equipmentName',
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
      {
        title: '公司名称',
        align: 'center',
        dataIndex: 'organizationName',
        width: 120,
        key: 'organizationId',
        valueType: 'select',
        options: { path: '/auth/sysDepartment/query/organization/selectbox', params: {} },
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
      {
        title: '部门名称',
        width: 120,
        align: 'center',
        valueType: 'select',
        dataIndex: 'departmentName',
        key: 'departmentId',
        options: {
          path: '/auth/sysDepartment/query/depart/selectbox',
          linkParams: {
            organizationId: 'parentId',
          },
        },
      },
      {
        title: '工厂名称',
        dataIndex: 'factoryName',
        key: 'factoryId',
        width: 120,
        align: 'center',
        valueType: 'select',
        options: { path: '/auth/sysFactory/getAllFactorySelection', params: {} },
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
      {
        title: '车间名称',
        dataIndex: 'shopName',
        align: 'center',
        width: 120,
        valueType: 'select',
        options: {
          path: '/auth/sysShop/getShopSelectionByFactory',
          linkParams: {
            factoryId: '',
          },
        },
        key: 'shopId',
        formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
      },
      {
        title: '工段名称',
        width: 120,
        dataIndex: 'sectionName',
        align: 'center',
        key: 'sectionId',
        valueType: 'select',
        options: {
          path: '/auth/sysSection/getAllSectionSelectionByShop',
          linkParams: {
            shopId: '',
          },
        },
      },
      {
        title: '产线名称',
        width: 120,
        dataIndex: 'productLineName',
        valueType: 'select',
        key: 'productLineName',
        align: 'center',
        options: {
          path: 'auth/sysProductionLine/getAllProductLineSelectionByShop',
          linkParams: {
            shopId: '',
          },
        },
      },
    ];
    return (
      <>
        <ProDescriptions
          request={async () => {
            const { data } = await doFetch({
              url: urlParams.detail,
              params: { id: drawer.item.id },
            });
            return {
              success: true,
              data: data.data,
            };
          }}
          columns={[
            {
              title: '设备编号',
              dataIndex: 'equipmentNo',
              key: 'equipmentNo',
            },
            {
              title: '设备名称',
              dataIndex: 'equipmentName',
              key: 'equipmentName',
            },
            {
              title: '位置号',
              dataIndex: 'positionNo',
              key: 'positionNo',
            },
            {
              title: '公司名称',
              dataIndex: 'organizationName',
              key: 'organizationId',
            },
            {
              title: '部门名称',
              dataIndex: 'departmentName',
              key: 'departmentId',
            },
            {
              title: '工厂名称',
              dataIndex: 'factoryName',
              key: 'factoryId',
            },
            {
              title: '车间名称',
              dataIndex: 'shopName',
              key: 'shopId',
            },
            {
              title: '工段名称',
              dataIndex: 'sectionName',
              key: 'sectionId',
            },
            {
              title: '产线名称',
              dataIndex: 'productLineName',
              key: 'productLineName',
            },
          ]}
        />
        <AutoTable
          pagetitle="选择子设备"
          columns={columns}
          path={urlParams_childEquipment.list}
          params={{ id: drawer?.item?.id }}
          resizeable={false}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys: selectArr,
            // defaultSelectedRowKeys: ,
            onSelect: (record, selected, selectedRows, nativeEvent) => {
              console.log('selectedRowKeys changed: ', record, selected, selectedRows);
              setSelectArr(() => {
                return selectedRows.map((it) => it.id);
              });
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
              console.log(selected, selectedRows, changeRows);
              if (selected) {
                let arr = selectArr.concat(changeRows.map((it) => it.id));
                setSelectArr(arr);
              } else {
                setSelectArr([]);
              }
            },
            onSelectNone: () => {
              console.log(11);
              setSelectArr([]);
            },
          }}
        />
        <Space style={{ marginTop: 16 }}>
          <Button
            onClick={() => {
              setDrawer((s) => ({
                ...s,
                visible: false,
                item: null,
                detailpath: null,
                params: null,
              }));
              setSelectArr([]);
            }}
          >
            取消
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              console.log(selectArr);
              let res = await doFetch({
                url: urlParams_childEquipment.save,
                params: {
                  equipmentId: drawer?.item?.id,
                  childrenIdList: selectArr,
                },
              });
              if (res.code === '0000') {
                message.success('新增成功！');
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                  item: null,
                }));
                setSelectArr([]);
                actionRef.current.reload();
              }
            }}
          >
            提交
          </Button>
        </Space>
      </>
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setDrawer);
    defcolumn[1].render = (text, row) => {
      return (
        <a
          onClick={() => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              // item: row,
              title: '详情',
              val: 'detail',
              detailpath: urlParams.detail,
              params: { id: row.id },
              title: row.equipmentName + '的详细信息',
            }));
          }}
        >
          {row.equipmentName}
        </a>
      );
    };
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      width: 200,
      render: (text, row, _, action) => [
        edit(text, row, _, action),
        remove(text, row, _, action),
        more(text, row, _, action),
      ],
    });
  }, []);

  const onselecteTree = async (selectedKeys, e, alldata) => {
    console.log(e.node);
    let params = {
      treeNodeType: e.node.type,
      treeNodeKey: e.node.key,
      pageSize: '15',
      pageIndex: '1',
    };
    const res = await doFetch({ url: urlParams.list, params });
    if (res.code === '0000') {
      message.success('新增成功！');
      setDrawer((s) => ({
        ...s,
        visible: false,
      }));
      actionRef.current.reload();
    }
  };

  return (
    <div style={{ position: 'relative' }}>
      <div className="ant-card-head">
        <div className="ant-card-head-wrapper">
          <div className="ant-card-head-title">
            <h3 className="page-title">设备台账</h3>
          </div>
        </div>
      </div>
      <Layout style={{ height: '100%' }}>
        <Sider theme="light" width={300}>
          <TreeRender url="/auth/sysFactory/getTree" onselected={onselecteTree} noaction={true} />
        </Sider>
        <Content>
          <AutoTable
            pagetitle={<h3 style={{ marginBottom: 0, fontWeight: 400 }}>设备台账</h3>}
            columns={columns}
            path={urlParams.list}
            actionRef={actionRef}
            pageextra={'add'}
            resizeable={false}
            addconfig={{
              // access: 'sysDepartment_save',
              btn: {
                disabled: false,
                type: 'primary',
                onClick: () => {
                  setDrawer((s) => ({
                    ...s,
                    visible: true,
                    item: null,
                    title: '新增',
                    val: 'add',
                    onFinish: async (vals) => {
                      console.log(vals);
                      let params = {
                        ...vals,
                      };
                      let res = await doFetch({
                        url: urlParams.save,
                        params,
                      });
                      if (res.code === '0000') {
                        message.success('新增成功！');
                        setDrawer((s) => ({
                          ...s,
                          visible: false,
                        }));
                        actionRef.current.reload();
                      }
                    },
                  }));
                },
              },
            }}
            x={1500}
          />
        </Content>
      </Layout>
      <DrawerPro
        fields={columns}
        // detailpath="/ngic-auth/sysUser/query/detail"
        // params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
            item: null,
            detailpath: null,
            params: null,
          }));
        }}
        {...drawer}
      >
        {drawer?.type == 'editChildEquipment' ? <EditChildEquipment /> : null}
      </DrawerPro>
    </div>
  );
}

export default Model;
