import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { CustomManageAPI } from '~/api';
import { Button, message, Modal, Rate, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { InterListType, InterReqListType } from '~/api/interface';
import { listUserApplyTag } from '~/api/interface/customManageType';
import ApprovalModal from './comp/approvalModal';
import AddEditModal from '~/pages/customManage/customIdentity/comp/addEditModal';

// 列表类型
type TableType = InterListType<listUserApplyTag>;
// 请求的参数
type ReqType = InterReqListType<listUserApplyTag>;
// 搜索表单的数据
let query: ReqType = {};
// 审批状态
const applyStatusList = [
  { label: '待审核', value: 0 },
  { label: '已通过', value: 1 },
  { label: '不通过', value: 2 },
];

const CustomIdentityView = () => {
  const { confirm } = Modal;
  // 加盟列表
  const [cooperationList, setCooperationList] = useState<{ label: string; value: number }[]>([]);
  // 新增编辑弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  //  审批弹窗
  const [approvalModalVisible, setApprovalModalVisible] = useState<boolean>(false);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await CustomManageAPI.listUserApplyTag({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // 获取加盟列表
  const getCooperationList = async () => {
    const res = await CustomManageAPI.cooperationListTag({});
    if (res && res.code === '200') {
      const list = res.result || [];
      setCooperationList(list.map((i) => ({ label: i.tagName, value: i.id })));
    }
  };
  // 删除数据
  const handleDelete = (record: TableType[0]) => {
    confirm({
      title: '提示',
      content: '是否删除该记录？',
      onOk: async () => {
        const res = await CustomManageAPI.deleteApplyTag({ id: record.id });
        if (res && res.code === '200') {
          message.success('删除成功');
          paginationChange(
            tableData.length === 1 ? pagination.current - 1 : pagination.current,
            pagination.pageSize,
          );
        }
      },
    });
  };
  useEffect(() => {
    getCooperationList().then();
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '序号',
      dataIndex: 'accountNo',
      align: 'center',
      width: '50px',
      render: (_text, _record, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '申请加盟类型',
      dataIndex: 'cooperationTagId',
      align: 'center',
      render: (text) => cooperationList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '企业认证名称',
      dataIndex: 'companyName',
      align: 'center',
      width: '200px',
      ellipsis: true,
    },
    {
      title: '联系人',
      dataIndex: 'applyName',
      align: 'center',
    },
    {
      title: '联系方式',
      dataIndex: 'applyPhone',
      align: 'center',
    },
    {
      title: '服务资质',
      dataIndex: 'content',
      align: 'center',
      width: '200px',
      ellipsis: true,
    },
    {
      title: '服务评价',
      dataIndex: 'score',
      align: 'center',
      width: '120px',
      render: (text) => text && <Rate disabled value={Number(text)} />,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      align: 'center',
    },
    {
      title: '审核状态',
      dataIndex: 'approvalStatus',
      align: 'center',
      render: (text) => applyStatusList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      width: '150px',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setApprovalModalVisible(true);
              setEditData(JSON.parse(JSON.stringify(record)));
            }}
            disabled={record.approvalStatus !== 0}
          >
            审批
          </Button>
          <Button
            type={'link'}
            onClick={() => {
              setAddModalVisible(true);
              setEditData(JSON.parse(JSON.stringify(record)));
            }}
            disabled={[0, 2].includes(record.approvalStatus)}
          >
            编辑
          </Button>
          <Button type={'link'} danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            name: 'companyName',
            label: '企业名称',
            type: 'input',
            placeholder: '请输入企业名称',
          },
          {
            name: 'cooperationTagId',
            label: '申请加盟类型',
            type: 'Select',
            placeholder: '请选择加盟类型',
            options: cooperationList,
          },
          {
            name: 'applyStatus',
            label: '申请状态',
            type: 'Select',
            placeholder: '请选择申请状态',
            options: applyStatusList,
          },
          {
            name: 'rangeTime',
            label: '申请时间',
            type: 'rangePicker',
            placeholder: '请选择开始时间和结束时间',
          },
        ]}
        searchData={onFinish}
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1200 }}
        bordered
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      {/*审批弹窗*/}
      <ApprovalModal
        open={approvalModalVisible}
        title={editData?.id ? '审批' : '新增'}
        data={editData}
        closed={() => {
          setApprovalModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
      {/*编辑弹窗*/}
      <AddEditModal
        open={addModalVisible}
        title={editData?.id ? '编辑' : '新增'}
        data={editData}
        closed={() => {
          setAddModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
    </>
  );
};

export default CustomIdentityView;
