import React, { useState, useRef } from "react";
import { message, Button, Popconfirm, FormInstance, InputNumber, Input } from "antd";
import { TableListItem, TableListPagination } from "./data";
import { queryRule, updateRule, removeRule, addRule, getAllInfoSettingValueBySettingName, exportEmployee } from "./service";
import UpdateForm, { FormValueType } from './components/UpdateForm';
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import Import from "@/components/Import/Import";
import Authorized from "@/utils/Authorized";

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在保存');

  if (!fields.id) {
    // eslint-disable-next-line no-param-reassign
    delete fields.id
    try {
      const msg = await addRule({...fields});
      hide();
      if (msg.retcode) {
        message.success('添加成功');
      } else {
        message.error('添加失败请重试！');
      }
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  } else {
    try {
      const msg = await updateRule({...fields});
      hide();
      if (msg.retcode) {
        message.success('保存成功');
      } else {
        message.error('保存失败请重试！');
      }
      return true;
    } catch (error) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }
};

/**
 *  批量导出
 * @param selectedRows
 */
const handleExportEmployee = async ({ ...params }: any) => {
  const hide = message.loading('正在导出');
  try {
    await exportEmployee(params);
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('处理失败，请重试');
    return false;
  }
};

/**
 * 删除节点
 * @param id 
 */
const handleRemove = async (id?: number) => {
  const hide = message.loading('正在删除');
  if (!id) return false;

  try {
    const msg = await removeRule({
      id
    });
    hide();
    if (msg.retcode) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败，请重试');
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const fetchData = async ({ ...params }: any) => {
  const msg = await queryRule(params);
  console.log(msg.data?.list)
  return {
    data: msg.data?.list || [],
    total: msg.data?.total || 0,
    success: msg.retcode,
  };
};

const UserList: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState({});
  const ref = useRef<FormInstance<TableListItem>>();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '姓名',
      width: 70,
      dataIndex: 'employeeName',
    },
    {
      title: '员工编号',
      width: 80,
      dataIndex: 'employeeNo',
    },
    {
      title: '手机号',
      width: 100,
      dataIndex: 'mobile',
    },
    {
      title: '出生日期',
      width: 80,
      dataIndex: 'birthday',
      search: false
    },
    {
      title: '性别',
      width: 60,
      dataIndex: 'sex',
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'sexes'
      },
      valueEnum: {
        1: '男',
        2: '女'
      }
    },
    {
      title: '年龄',
      width: 60,
      dataIndex: 'age',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'ages'
      },
      renderFormItem: (_, { type }, form) => {
        if (type === 'form') {
          return null;
        }
        let value1 = form.getFieldValue('ages') ? form.getFieldValue('ages')[0] : '';
        let value2 = form.getFieldValue('ages') ? form.getFieldValue('ages')[1] : '';
        return (
          <Input.Group compact>
            <InputNumber
              {...{
                value: value1,
                min: 0,
                onChange: (e) => {
                  value1 = e;
                  const newValues: any = {};
                  newValues.ages = [value1, value2];
                  form.setFieldsValue(newValues);
                },
              }}
              style={{ width: 100, textAlign: 'center' }}
            />
            <Input
              style={{
                width: 30,
                borderLeft: 0,
                borderRight: 0,
                pointerEvents: 'none',
              }}
              placeholder="~"
              disabled
            />
            <InputNumber
              {...{
                value: value2,
                min: 0,
                onChange: (e) => {
                  value2 = e;
                  const newValues: any = {};
                  newValues.ages = [value1, value2];
                  form.setFieldsValue(newValues);
                },
              }}
              style={{
                width: 100,
                textAlign: 'center',
              }}
            />
          </Input.Group>
        );
      },
    },
    {
      title: '部门',
      dataIndex: 'departmentId',
      width: 120,
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'departmentIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '部门'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '单位',
      width: 320,
      dataIndex: 'unitId',
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'unitIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '单位'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '现岗位',
      width: 110,
      dataIndex: 'postId',
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'postIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '岗位'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '班组',
      width: 140,
      dataIndex: 'groupsId',
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'groupsIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '班组'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '最高学历',
      dataIndex: 'highestEducationId',
      width: 110,
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'highestEducationIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '学历'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '专业技术资格',
      dataIndex: 'ptqId',
      valueType: 'select',
      width: 130,
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'ptqIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '专业技术资格'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '技能等级',
      dataIndex: 'skillLevelId',
      valueType: 'select',
      width: 80,
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'skillLevelIds'
      },
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '技能等级'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.id
            }
          })
        }
        return []
      }
    },
    {
      title: '奖惩等级',
      dataIndex: 'honorLevel',
      valueType: 'select',
      fieldProps: {
        mode: "multiple"
      },
      formItemProps: {
        name: 'honorLevels'
      },
      hideInTable: true,
      request: async () => {
        const msg = await getAllInfoSettingValueBySettingName({settingName: '奖惩等级'})
        if (msg.retcode && msg.data) {
          return msg.data.map((e: any) => {
            return {
              label: e.settingValue,
              value: e.settingValue
            }
          })
        }
        return []
      }
    },
    {
      title: '奖惩内容',
      dataIndex: 'honorDescription',
      hideInTable: true,
    },
    {
      title: "操作",
      dataIndex: "option",
      width: 80,
      hideInSearch: true,
      render: (text: any, record: TableListItem) => (
        <span>
          <a style={{ marginRight: 8 }} onClick={()=>{
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}>编辑</a>
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Popconfirm title="确定删除?" onConfirm={async () => {
              const success = await handleRemove(record.id)
              if (success) actionRef.current?.reload()
            }}>
              <a style={{color: 'red'}}>删除</a>
            </Popconfirm>
          </Authorized>
        </span>
      )
    }
  ];
  return (
    <>
      <ProTable<TableListItem, TableListPagination>
        headerTitle={null}
        actionRef={actionRef}
        rowKey="id"
        options={false}
        formRef={ref}
        scroll={{
          y: 'calc(100vh - 500px)'
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        search={{
          collapsed: false,
          collapseRender: false,
          labelWidth: 'auto'
        }}
        toolBarRender={() => [
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleUpdateModalVisible(true);
                setCurrentRow({
                  id: undefined,
                });
              }}
            >
              新增
            </Button>
          </Authorized>,
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Import
              api={'/api/employee/importEmployee'}
              text="批量导入员工基本信息"
              uploaded={() => {
                actionRef.current?.reload();
              }}
            />
          </Authorized>,
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Import
              api={'/api/educationResume/importEducationResume'}
              text="批量导入员工教育履历"
              uploaded={() => {
                actionRef.current?.reload();
              }}
            />
          </Authorized>,
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Import
              api={'/api/familyMembers/importFamilyMembers'}
              text="批量导入员工家庭成员"
              uploaded={() => {
                actionRef.current?.reload();
              }}
            />
          </Authorized>,
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Import
              api={'/api/workExperience/importWorkExperience'}
              text="批量导入员工工作经历记录"
              uploaded={() => {
                actionRef.current?.reload();
              }}
            />
          </Authorized>,
          <Authorized authority="employeeSave" noMatch={<span />}>
            <Import
              api={'/api/honor/importHonor'}
              text="批量导入员工奖惩记录"
              uploaded={() => {
                actionRef.current?.reload();
              }}
            />
          </Authorized>,
          <Button
            key="export"
            type="primary"
            onClick={() => {
              const values = ref.current?.getFieldsValue();

              handleExportEmployee(values);
            }}
          >
            导出
          </Button>,
        ]}
        request={fetchData}
        columns={columns}
      />
      {currentRow && Object.keys(currentRow).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setCurrentRow({});

              actionRef.current?.reload()
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setCurrentRow({});
          }}
          updateModalVisible={updateModalVisible}
          values={currentRow}
        />
      ) : null}
    </>
  )
}

export default UserList;
