import React, { useEffect, useState } from 'react';
import { Table, Button, message, Switch, Popconfirm } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { getCoscoSupplierUserPage, editType, coscoSupplierUserDel } from '../services';
import { useIntl } from 'umi';
import ContactsInfoFormModal from './ContactsInfoFormModal';

interface getCoscoSupplierUser {
  id: string;
  attachmentsType?: string;
  fileName?: string;
  filePath?: string;
  fileSize?: string;
  fileType?: string;
  fileUrl?: string;
  supplierId?: string;
  certificateUrl?: string;
  delFlag: string;
  type: string;
}

interface Props {
  viewType?: boolean;
  record?: string;
}
const OtherAttachmentsTab: React.FC<Props> = (props) => {
  const userId = sessionStorage.getItem('userId') || '';
  const { viewType = false, record = userId } = props;
  //语言切换
  const intl = useIntl();
  //列表渲染数据
  const [data, setData] = useState<getCoscoSupplierUser[]>([]);
  //列表加载
  const [loading, setLoading] = useState(false);
  //列表分页
  const [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });

  //列表方法
  const getList = async (pageNo = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const { code, data } = await getCoscoSupplierUserPage({ pageNo, pageSize, supplierId: record });
      if (code === 200) {
        setData(data.records);
        setPagination({ current: pageNo, pageSize, total: data.total });
      }
    } finally {
      setLoading(false);
    }
  };

  //增改查
  const [formVisible, setFormVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<getCoscoSupplierUser | null>(null);
  const [isViewMode, setIsViewMode] = useState(false);
  const handleFormSubmit = () => {
    setFormVisible(false);
    getList();
  };
  //新增
  const handleAdd = () => {
    setEditingRecord(null);
    setIsViewMode(false);
    setFormVisible(true);
  };
  //  修改
  const handleEdit = (record: getCoscoSupplierUser) => {
    setEditingRecord(record);
    setIsViewMode(false);
    setFormVisible(true);
  };
  //  查看
  const handleView = (record: getCoscoSupplierUser) => {
    setEditingRecord(record);
    setIsViewMode(true);
    setFormVisible(true);
  };
  //删除
  const handleDel = (record: getCoscoSupplierUser) => {
    coscoSupplierUserDel(record.id).then((res) => {
      if (res.code == 200) {
        message.success('删除成功');
        getList();
      }
    })
  };
  //是否为主联系人
  const handleObsoleteChange = async (checked: boolean, id: string) => {
    // 调用你的作废接口
    const res = await editType({ id, supplierId: record });
    if (res.code === 200) {
      message.success('操作成功');
      getList(pagination.current, pagination.pageSize);  // 刷新列表
    } else {
      message.error('操作失败');
    }
  }
  //初始化
  useEffect(() => {
    if (record) {
      getList();
    }
  }, [record]);


  const columns: ColumnsType<getCoscoSupplierUser> = [
    {
      title: intl.formatMessage({ id: 'page.workbench.attachments.index' }),
      render: (_: any, __: any, index: number) => index + 1,
      width: 60,
    },
    {
      title: '联系人',
      dataIndex: 'contactsName',
      key: 'contactsName',
    },
    {
      title: '手机号',
      dataIndex: 'contactsPhone',
      key: 'contactsPhone',
    },
    {
      title: '邮箱',
      dataIndex: 'contactsEmail',
      key: 'contactsEmail',
    },

    {
      title: '是否为主联系人',
      dataIndex: 'type',
      align: 'center',
      width: 180,
      render: (value, record: getCoscoSupplierUser) => {
        let checkedType = value === '1' ? true : false;
        return (
          <Switch
            checked={checkedType}
            disabled={viewType}
            onChange={(checked) => handleObsoleteChange(checked, record.id)}
          />
        )

      },
    },
    ...(viewType ? [] : [
      {
        title: 'page.workbench.attachments.action',
        dataIndex: 'option',
        width: 140,
        render: (_: any, record: getCoscoSupplierUser) => {

          return (
            <>
              <a style={{ marginRight: 8 }} onClick={() => handleView(record)}>查看</a>

              <a style={{ marginRight: 8 }} onClick={() => handleEdit(record)}>修改</a>

              {record.type === '0' && (
                <Popconfirm
                  title="确定要删除该联系人吗？"
                  onConfirm={() => handleDel(record)}
                >
                  <a >删除</a>
                </Popconfirm>
              )}
            </>
          )
        }
      }
    ])
  ];
  return (
    <div style={{ padding: '0 30px 0 0' }}>
      <div style={{ marginBottom: 16 }}>
        {!viewType && (
          <Button type="primary" onClick={handleAdd}>新增</Button>
        )}
      </div>
      <Table
        className="custom-table"
        rowKey="id"
        columns={columns.map(column => ({
          ...column,
          title: intl.formatMessage({ id: column.title as string })
        }))}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={(pagination) => getList(pagination.current!, pagination.pageSize!)}
      />
      <ContactsInfoFormModal
        visible={formVisible}
        onOk={handleFormSubmit}
        onCancel={() => setFormVisible(false)}
        initialValues={editingRecord || undefined}
        readOnly={isViewMode}
      />
    </div>
  );
};

export default OtherAttachmentsTab;