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 { InterDataType, InterListType, InterReqListType } from '~/api/interface';
import { listAppUserCountType, listUserApplyTag } from '~/api/interface/customManageType';
import ApprovalModal from './comp/approvalModal';
import AddEditModal from '~/pages/customManage/customIdentity/comp/addEditModal';
import ContractModal from '~/pages/customManage/customIdentity/comp/contractModal';
import './index.scss';

// 列表类型
type TableType = InterListType<listUserApplyTag>;
// 请求的参数
type ReqType = InterReqListType<listUserApplyTag>;
// 统计数据返回类型
type statisticsDataType = InterDataType<listAppUserCountType>;

// 搜索表单的数据
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 [statisticsData, setStatisticsDataType] = useState<statisticsDataType>();
  // 合同弹窗
  const [contractModalShow, setContractModalShow] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);

  // 加载列表
  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 () => {
    setLoading(true);
    const res = await CustomManageAPI.cooperationListTag({});
    setLoading(false);
    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,
          );
          getListAppUserCount();
        }
      },
    });
  };
  // 商家加盟状态数据统计
  const getListAppUserCount = () => {
    CustomManageAPI.getListAppUserCount().then(({ result }) => {
      if (result) {
        setStatisticsDataType(result);
      }
    });
  };
  // 合同签署
  const contractModalShowClick = (record: TableType[0]) => {
    setEditData(record);
    setContractModalShow(true);
  };
  const contractModalCancel = () => {
    setContractModalShow(false);
  };
  const contractModalOk = () => {
    setContractModalShow(false);
    getTableList(query).then();
  };

  useEffect(() => {
    query = {};
    getCooperationList().then();
    getTableList().then();
    getListAppUserCount();
  }, []);
  // 表格结构
  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',
      width: '100px',
    },
    {
      title: '企业简称',
      dataIndex: 'brandName',
      align: 'center',
      width: '100px',
      ellipsis: true,
    },
    {
      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: '200px',
      render: (_text, record) => (
        <>
          <Button
            type={'link'}
            onClick={() => {
              setApprovalModalVisible(true);
              setEditData(JSON.parse(JSON.stringify(record)));
            }}
            disabled={record.approvalStatus !== 0}
          >
            审批
          </Button>
          <Button
            type='link'
            onClick={() => contractModalShowClick(record)}
            disabled={record.approvalStatus !== 1 || [2, 3, 4, 5].includes(record.signStatus)}
          >
            签署合同
          </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 (
    <div className='custom-identity'>
      <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}
        sufFixBtn={
          <div className='data-statistics'>
            <div>
              <span>已通过：</span>
              <span>{statisticsData?.passAuditSum || 0}</span>
            </div>
            <div>
              <span>审批中：</span>
              <span>{statisticsData?.unAuditedSum || 0}</span>
            </div>
            <div>
              <span>未通过：</span>
              <span>{statisticsData?.failAuditSum || 0}</span>
            </div>
          </div>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        loading={loading}
        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);
          getListAppUserCount();
          (window as any).getMessageNumber();
        }}
      />
      {/*编辑弹窗*/}
      <AddEditModal
        open={addModalVisible}
        title={editData?.id ? '编辑' : '新增'}
        data={editData}
        closed={() => {
          setAddModalVisible(false);
          setEditData(undefined);
          paginationChange(pagination.current, pagination.pageSize);
        }}
      />
      {/*合同签署*/}
      <ContractModal
        open={contractModalShow}
        onCancel={contractModalCancel}
        onOk={contractModalOk}
        joinItem={editData}
      />
    </div>
  );
};

export default CustomIdentityView;
