import React, { useEffect, useState } from 'react';
import './index.scss';
import { Button, Form, Input, message, Select, Table } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ColumnsType } from 'antd/es/table';
import { IndustryManageAPI } from '~/api';
import { IndustrySkuType } from './propsType';
import AddOrEditIndustryModal from './components/addOrEditIndustryModal';
// import DeleteModal from '@/components/DeleteModal';
import useOption from '~/common/hook/optionHook';

const { Option } = Select;
// 搜索表单的数据
let query: any = {};

// 表单提交
interface FormType {
  goodsTypeId?: number;
  solutionName?: string;
}

function IndustryList() {
  // 路由操作
  const navigate = useNavigate();
  // 表格数据
  const [tableData, setTableData] = useState<any>([{ id: 1 }]);
  // 加载中
  const [loading, setLoading] = useState<boolean>(false);
  // 行业列表
  const [industryType, setIndustryType] = useState<{ label: string; val: number }[]>([]);
  // 行业列表对象
  const [industryTypeObj, setIndustryTypeObj] = useState<any>({});
  // 跳转详情
  const handleDetail = (record: { id: number }) => {
    navigate({
      pathname: '/mallManage/industryDetail',
      search: `id=${record.id}`,
    });
    // console.log(record);
  };
  // 删除弹窗是否显示
  const [visibleDeleteModal, setVisibleDeleteModal] = useState<boolean>(false);
  // 当前操作方案
  const [curtRow, setCurtRow] = useState<IndustrySkuType>({
    goodsTypeId: undefined,
    description: '',
    solutionName: '',
    createTime: '',
    id: 0,
  });
  // 表格结构
  const columns: ColumnsType<IndustrySkuType> = [
    { title: '方案名称', dataIndex: 'solutionName', align: 'center' },
    {
      title: '所属行业',
      align: 'center',
      render: (text: string, record) => {
        return (
          <div>{industryTypeObj[record.goodsTypeId as keyof typeof industryTypeObj] || ''}</div>
        );
      },
    },
    { title: '描述', dataIndex: 'description', align: 'center' },
    {
      title: '操作',
      align: 'center',
      width: '15%',
      fixed: 'right',
      render: (text: string, record) => {
        return (
          <div>
            <Button type='link' onClick={() => handleDetail(record)}>
              详情
            </Button>
            <Button type='link' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='link' onClick={() => openDeleteModal(record)}>
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 按钮权限
  const btnAdd = useOption(22201);
  const btnDelete = useOption(22202);
  const btnEdit = useOption(22203);
  const btnDetail = useOption(22204);

  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    setLoading(true);
    // 只需要修改这个地方的接口即可
    const res: any = await IndustryManageAPI.listPageIndustrySku({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    setLoading(false);
    if (res && res.code === '200') {
      // console.log("res -->", res);
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        pageSize,
        current: pageNo,
        totalPage,
      });
      setTableData(list);
    } else {
      message.warning(res.message);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (val: FormType) => {
    // 在这里对提交的数据做处理，如range转为开始和结束时间
    const data = Object.fromEntries(
      // 过滤为空项
      Object.entries({
        ...val,
      }).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    query = data;
    getTableList(data).then();
  };

  // 获取所属行业下拉列表
  const getFirstIndustryTypeInfo = async () => {
    const res: any = await IndustryManageAPI.getFirstIndustryTypeInfo({});
    if (res && res.code === '200') {
      const arr = res.result.map((i: { goodsMasterType: string; goodsMasterTypeId: number }) => {
        return {
          label: i.goodsMasterType,
          val: i.goodsMasterTypeId,
        };
      });
      const obj = res.result.reduce((prev: any, curt: any) => {
        prev[curt.goodsMasterTypeId] = curt.goodsMasterType;
        return prev;
      }, {});
      setIndustryType(arr);
      setIndustryTypeObj(obj);
    }
  };

  // 新增弹窗是否显示
  const [visibleAddEdit, setVisibleAddEdit] = useState(false);
  // 新增弹窗内容
  const [addEditData, setAddEditData] = useState<IndustrySkuType>({
    goodsTypeId: undefined,
    description: '',
    solutionName: '',
    createTime: '',
    id: 0,
  });
  // 新增弹窗
  const handleAdd = () => {
    setVisibleAddEdit(true);
    setAddEditData({
      createTime: '',
      goodsTypeId: undefined,
      description: '',
      solutionName: '',
      id: 0,
    });
  };
  // 编辑弹窗
  const handleEdit = (record: IndustrySkuType) => {
    setVisibleAddEdit(true);
    setAddEditData(record);
  };
  // 关闭弹窗
  const handleAddEditClosed = () => {
    setVisibleAddEdit(false);
    setAddEditData({
      createTime: '',
      goodsTypeId: undefined,
      description: '',
      solutionName: '',
      id: 0,
    });
    paginationChange(pagination.current, pagination.pageSize);
  };
  // 删除弹窗是否显示

  // 打开删除弹窗
  const openDeleteModal = (record: IndustrySkuType) => {
    setVisibleDeleteModal(true);
    setCurtRow(record);
  };
  // 关闭删除弹窗
  const handleDeleteSkuClosed = () => {
    setVisibleDeleteModal(false);
  };
  // 删除行业方案
  const handleDeleteSku = async () => {
    const res: any = await IndustryManageAPI.removeIndustrySku({ id: curtRow.id });
    if (res.code === '200') {
      message.success('操作成功');
      handleDeleteSkuClosed();
      getTableList().then();
    } else {
      message.error(res.message);
      handleDeleteSkuClosed();
    }
  };

  // componentDidMount
  useEffect(() => {
    // query = {};
    // (async () => {
    //   await getFirstIndustryTypeInfo();
    //   await getTableList();
    // })();
  }, []);

  return (
    <div className='from-table-wrap'>
      <div className='header-view'>
        <Form name='basic' layout='inline' onFinish={onFinish}>
          {btnAdd || true ? (
            <Form.Item>
              <Button type='primary' onClick={handleAdd}>
                新增
              </Button>
            </Form.Item>
          ) : (
            ''
          )}

          <Form.Item name='solutionName' label='方案名称'>
            <Input placeholder='请输入方案名称' allowClear />
          </Form.Item>
          <Form.Item name='goodsTypeId' label='所属行业'>
            <Select placeholder='请选择所属行业' allowClear>
              {industryType.map((i, j) => (
                <Option value={i.val} key={j}>
                  {i.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit'>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1500 }}
        bordered
        loading={loading}
        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} 条数据`,
        }}
      />

      <AddOrEditIndustryModal
        visible={visibleAddEdit}
        closed={handleAddEditClosed}
        data={addEditData}
      />

      {/*<DeleteModal*/}
      {/*  visible={visibleDeleteModal}*/}
      {/*  onCancel={handleDeleteSkuClosed}*/}
      {/*  onOK={handleDeleteSku}*/}
      {/*/>*/}
    </div>
  );
}
export default IndustryList;
