import React, { useState, useRef, forwardRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Modal, Form, Select, Table, Card, Row, Col, Input, Button, message } from 'antd';
import { columns, repastTypeList } from './data';
import EditRepastModal from './editRepastModal';
import AddModal from './addModal';
import styles from './index.less';
import {
  setShopList,
  setShopDelete,
  mealTypeList,
  apiEnterpriseList,
  busineesTypeCheck,
} from './service.js';

const { confirm } = Modal;
const StoreManagement = () => {
  const [page, setPage] = useState({
    page: 1,
    size: 10,
  });
  const [searchForm, setSearchForm] = useState({});
  const formRef = useRef(null);
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [repastType, setRepastType] = useState([]);
  const [repastId, setRepastId] = useState(null);
  const [enterpriseList, setEnterpriseList] = useState();
  const [firstEnterprise, setFirstEnterprise] = useState('');
  const [enterprise, setEnterprise] = useState({});
  const [dataList, setDataList] = useState([]);
  const [name, setName] = useState('');

  const shopList = async () => {
    const params = {
      ...page,
      data: searchForm,
    };
    const res = await setShopList(params);
    if (res.businessCode === '0000') {
      setDataList(res.data?.records);
    }
  };

  // 企业查询
  const getEnterpriseList = async () => {
    const res = await apiEnterpriseList();
    if (res.businessCode === '0000' && res.data?.records?.length) {
      const list = res.data.records;
      const firstOption = list[0].id;
      const optionData = list.map(item => ({
        value: item.id,
        label: item.name,
      }));
      setFirstEnterprise(firstOption);
      setEnterpriseList(optionData);
      setSearchForm({ enterpriseId: firstOption });
      shopList();
    }
  };
  useEffect(() => {
    getEnterpriseList();
  }, []);

  useEffect(() => {
    shopList();
  }, [searchForm, page]);
  // 关闭弹框
  const closeModal = value => {
    if (value) {
      shopList();
    }
    setEditVisible(false);
    setAddVisible(false);
  };
  const setMealTypeList = async () => {
    setEditVisible(true);
    const res = await mealTypeList({ id: repastId });
    if (res.businessCode === '0000') {
      setRepastType(res.data);
      setEditVisible(true);
    }
  };
  // 修改餐饮类型
  const editRepastType = ({ id }) => {
    setRepastId(id);
    setMealTypeList();
  };
  // 删除
  const editShop = async id => {
    const res = await setShopDelete({ id });
    if (res.businessCode === '0000') {
      message.success('删除成功！');
      shopList();
    }
  };
  // 删除
  const delShop = ({ shopName, id }) => {
    confirm({
      title: `确认删除企业商户#${shopName || ''}#?`,
      content: '注：删除微店后，其商户下企业商品一并删除',
      onOk() {
        editShop(id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const onChange = (value, option) => {
    setEnterprise(option);
  };
  // 添加商户
  const addShop = async () => {
    const res = await busineesTypeCheck({ id: searchForm.id });
    if (res.businessCode === '0000') {
      const val = enterpriseList.find(item => item.value === searchForm.enterpriseId).label;
      setName(val);
      setAddVisible(true);
    }
  };
  // 搜索
  const onFinish = async values => {
    setSearchForm(values);
    setPage({ current: 1, pageSize: 10 });
  };
  // 重置
  const onReset = () => {
    formRef.current.resetFields();
    setSearchForm({ enterpriseId: firstEnterprise });
  };
  // 分页
  const handleTableChange = val => {
    setPage(val);
  };

  const res = {
    editRepastType,
    delShop,
  };
  return (
    <PageHeaderWrapper>
      <Card className={styles.card}>
        {firstEnterprise && (
          <Form ref={formRef} onFinish={onFinish}>
            <Row gutter={24}>
              <Col span={8}>
                <Form.Item
                  label="企业名称"
                  name="enterpriseId"
                  wrapperCol={{ span: 16 }}
                  rules={[{ required: true }]}
                  initialValue={firstEnterprise}
                >
                  <Select
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    onChange={onChange}
                    options={enterpriseList}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="微店名称" name="shopName" wrapperCol={{ span: 16 }}>
                  <Input maxLength="20" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="微店ID" name="shopId" wrapperCol={{ span: 16 }}>
                  <Input maxLength="20" allowClear />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="餐品类型" name="mealType" wrapperCol={{ span: 16 }}>
                  <Select
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                    options={repastTypeList}
                    placeholder="全部"
                  />
                </Form.Item>
              </Col>
              <Col className={styles.btn}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button htmlType="button" onClick={onReset} className={styles.left}>
                    重置
                  </Button>
                  <Button type="primary" onClick={addShop} className={styles.left}>
                    添加商户
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}
      </Card>
      <Table
        columns={columns(res)}
        dataSource={dataList}
        rowKey={r => r.appealNo}
        bordered
        onChange={handleTableChange}
      />
      <EditRepastModal
        editVisible={editVisible}
        repastType={repastType}
        id={repastId}
        onCancel={closeModal}
      />
      <AddModal addVisible={addVisible} name={name} onCancel={closeModal} />
    </PageHeaderWrapper>
  );
};
export default StoreManagement;
