import React, { Fragment, useEffect, useRef, useState } from 'react';
import { FormattedMessage, useAccess } from '@umijs/max';
import { Button, Descriptions, FormInstance, message, Modal } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { AlignLeftOutlined, DeleteOutlined, FormOutlined, PlusOutlined } from '@ant-design/icons';
import EditCompanyListRow from './edit';
import {
  addCmsCompanyList,
  delCmsCompanyList,
  exportCmsCompanyList,
  getCmsCompanyList,
  putCmsCompanyList,
} from '@/services/company/list';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import { getCmsIndustryTreeList } from '@/services/classify/industry';

// 详情查看组件
const CompanyDetailModal = ({
  visible,
  onCancel,
  record,
  scaleEnum,
  industryEnum,
}: {
  visible: boolean;
  onCancel: () => void;
  record?: API.CompanyList.Company;
  scaleEnum: Record<string, any>;
  industryEnum: Record<string, any>;
}) => {
  return (
    <Modal
      title="公司详情"
      open={visible}
      width={600}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          关闭
        </Button>,
      ]}
    >
      <Descriptions column={1} bordered>
        <Descriptions.Item label="公司名称">{record?.name}</Descriptions.Item>
        <Descriptions.Item label="公司行业">
          <DictTag enums={industryEnum} value={record?.industry} />
        </Descriptions.Item>
        <Descriptions.Item label="公司规模">
          <DictTag enums={scaleEnum} value={record?.scale} />
        </Descriptions.Item>
        <Descriptions.Item label="公司位置">{record?.location}</Descriptions.Item>
      </Descriptions>
    </Modal>
  );
};

function ManagementList() {
  const access = useAccess();

  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<API.CompanyList.Company>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [scaleEnum, setScaleEnum] = useState<Record<string, any>>({});
  const [industryEnum, setIndustryEnum] = useState<Record<string, any>>({});

  const handleRemoveOne = async (jobId: string) => {
    const hide = message.loading('正在删除');
    if (!jobId) return true;
    try {
      const resp = await delCmsCompanyList(jobId);
      hide();
      if (resp.code === 200) {
        message.success('删除成功，即将刷新');
      } else {
        message.error(resp.msg);
      }
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleExport = async (values: API.CompanyList.Params) => {
    const hide = message.loading('正在导出');
    try {
      await exportCmsCompanyList(values);
      hide();
      message.success('导出成功');
      return true;
    } catch (error) {
      hide();
      message.error('导出失败，请重试');
      return false;
    }
  };

  useEffect(() => {
    getDictValueEnum('scale', true, true).then((data) => {
      console.log(data,'______')
      setScaleEnum(data);
    });
    getCmsIndustryTreeList().then((res) => {
    
      let dict = []
      try {
        res.data.forEach(item => {
         dict[item.id] = {
           label: item.label,
           text: item.label,
           value: item.id,
           listClass: "default",
           status: "default",
         };
        });
      } catch (error) {
        dict = []
      }
      console.log(dict,'+++++')
      setIndustryEnum(dict);
    });
  }, []);

  const columns: ProColumns<API.CompanyList.Company>[] = [
    {
      title: '公司名称',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
    },
    // {
    //   title: '公司行业',
    //   hideInSearch: true,
    //   dataIndex: 'industry',
    //   valueType: 'text',
    //   align: 'center',
    // },
    {
      title: '公司规模',
      dataIndex: 'scale',
      valueType: 'select',
      align: 'center',
      valueEnum: scaleEnum,
      render: (_, record) => {
        return <DictTag enums={scaleEnum} value={record.scale} />;
      },
    },
    {
      title: '公司位置',
      dataIndex: 'location',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'companyId',
      width: 300,
      render: (companyId, record) => [
        <Button
          type="link"
          size="small"
          key="detail"
          icon={<AlignLeftOutlined />}
          hidden={!access.hasPerms('area:business:List.view')}
          onClick={() => {
            setCurrentRow(record);
            setDetailVisible(true);
          }}
        >
          详情
        </Button>,
        <Button
          type="link"
          size="small"
          key="edit"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('area:business:List.update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          key="batchRemove"
          icon={<DeleteOutlined />}
          hidden={!access.hasPerms('area:subway:List')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(companyId as string);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.CompanyList.Company>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="companyId"
          key="index"
          columns={columns}
          request={(params) =>
            getCmsCompanyList({ ...params } as API.CompanyList.Params).then((res) => {
              return {
                data: res.rows,
                total: res.total,
                success: true,
              };
            })
          }
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('manage:List:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
            <Button
              type="primary"
              key="export"
              hidden={!access.hasPerms('system:user:export')}
              onClick={async () => {
                const searchVal = formTableRef.current?.getFieldsValue();
                handleExport(searchVal as API.CompanyList.Params);
              }}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            </Button>,
          ]}
        />
      </div>

      <EditCompanyListRow
        open={modalVisible}
        onSubmit={async (values) => {
          let resData;
          if (values.companyId) {
            resData = await putCmsCompanyList(values);
          } else {
            resData = await addCmsCompanyList(values);
          }
          if (resData.code === 200) {
            setModalVisible(false);
            setCurrentRow(undefined);
            message.success(values.companyId ? '修改成功' : '新增成功');
            actionRef.current?.reload();
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        values={currentRow}
        scaleEnum={scaleEnum}
      />

      <CompanyDetailModal
        visible={detailVisible}
        onCancel={() => {
          setDetailVisible(false);
          setCurrentRow(undefined);
        }}
        record={currentRow}
        scaleEnum={scaleEnum}
        industryEnum={industryEnum}
      />
    </Fragment>
  );
}

export default ManagementList;
