import React, { Fragment, useEffect, useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import { Button, FormInstance, message, Modal, Switch, Tooltip } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { DeleteOutlined, FormOutlined, PieChartFilled, PlusOutlined } from '@ant-design/icons';
import EditCompanyListRow from './edit';
import { delCmsCompanyList } from '@/services/company/list';
import { getDictValueEnum } from '@/services/system/dict';
import {
  addCmsCardList,
  delCmsCardList,
  getCmsCardList,
  putCmsCardList,
} from '@/services/application/preproducts';

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

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

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

  const [currentRow, setCurrentRow] = useState<API.ApplicationProducts.Product>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [companyNatureEnum, setCompanyNatureEnum] = useState<any>([]);
  const [companyLabelEnum, setCompanyLabelEnum] = useState<any>([]);
  const [enableStatusEnum, setEnableStatusEnum] = useState<any>([]);

  useEffect(() => {
    getDictValueEnum('company_nature', true, true).then((data) => {
      setCompanyNatureEnum(data);
    });
    getDictValueEnum('company_label', true, true).then((data) => {
      setCompanyLabelEnum(data);
    });
    getDictValueEnum('enable_status', true).then((data) => {
      setEnableStatusEnum(data);
    });
  }, []);

  const changeStatus = async (record: API.ApplicationProducts.Product) => {
    let resData = await putCmsCardList({
      companyCardId: record.companyCardId,
      status: record.status === 1 ? 0 : 1,
    });
    if (resData.code === 200) {
      message.success('修改成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  const columns: ProColumns<API.ApplicationProducts.Product>[] = [
    {
      title: '卡片名称',
      dataIndex: 'name',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '卡片颜色',
      dataIndex: 'backgroudColor',
      valueType: 'text',
      align: 'center',
      render: (text, _) => <PieChartFilled style={{ color: text }} />,
    },
    {
      title: '排序',
      dataIndex: 'cardOrder',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      valueType: 'select',
      align: 'center',
      valueEnum: enableStatusEnum,
      render: (text, record) => (
        <Switch checked={record.status === 1} onChange={changeStatus.bind(null, record)} />
      ),
    },
    {
      title: '精选描述',
      dataIndex: 'description',
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text} placement="topLeft">
          <span>{text || '-'}</span>
        </Tooltip>
      ),
      hideInSearch: true, 
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'companyCardId',
      width: 300,
      render: (companyCardId, record) => [
        <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 delCmsCardList(companyCardId as string);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },

  ];
  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.ApplicationProducts.Product>
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="companyCardId"
          key="index"
          columns={columns}
          request={(params) =>
            getCmsCardList({ ...params } as API.ApplicationProducts.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>,
          ]}
        />
      </div>
      <EditCompanyListRow
        open={modalVisible}
        onSubmit={async (values) => {
          let resData;
          if (values.companyCardId) {
            resData = await putCmsCardList(values);
          } else {
            resData = await addCmsCardList(values);
          }
          if (resData.code === 200) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (values.companyCardId) {
              message.success('修改成功');
            } else {
              message.success('新增成功');
            }
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        values={currentRow}
        companyLabelEnum={companyLabelEnum}
        companyNatureEnum={companyNatureEnum}
        enableStatusEnum={enableStatusEnum}
      ></EditCompanyListRow>
    </Fragment>
  );
}

export default ManagementList;
