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 { set } from 'lodash';
import { da } from 'date-fns/locale';
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 [total, setTotal] = useState(0);
  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 [isStore, setIsStore] = useState(false);
  const shopList = async params => {
    const res = await setShopList(params);
    if (res.businessCode === '0000') {
      setDataList(res.data?.records);
      setTotal(res.data?.total);
    }
  };

  // 企业查询
  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,
      }));
      setEnterprise({ value: list[0].id, label: list[0].name });
      setFirstEnterprise(firstOption);
      setEnterpriseList(optionData);
      setSearchForm({ enterpriseId: firstOption });
      shopList({ data: { enterpriseId: firstOption }, ...page });
    }
  };
  useEffect(() => {
    getEnterpriseList();
  }, []);

  // 关闭弹框
  const closeModal = (status, val) => {
    if (status) {
      const pageInfo = {
        page: 1,
        size: 10,
      };
      setPage(pageInfo);
      shopList({ data: searchForm, ...pageInfo });
    }
    if (val === 'edit') {
      setIsStore(false);
      setEditVisible(false);
      setRepastType([]);
      return;
    }
    setName(false);
    setAddVisible(false);
  };
  const setMealTypeList = async id => {
    const res = await mealTypeList({ id });
    if (res.businessCode === '0000') {
      const resData = res.data;
      const data = [];
      repastTypeList.forEach(item => {
        if (resData.includes(item.value) && item.value !== 4) {
          data.push(item);
        }
      });
      if (resData.includes(4)) {
        setIsStore(true);
      }
      setRepastType(data);
      setEditVisible(true);
    }
  };
  // 修改餐饮类型
  const editRepastType = ({ id }) => {
    setRepastId(id);
    setMealTypeList(id);
  };
  // 删除
  const editShop = async id => {
    const res = await setShopDelete({ id });
    if (res.businessCode === '0000') {
      message.success('删除成功！');
      shopList({ ...page, data: searchForm });
    }
  };
  // 删除
  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({ enterpriseId: searchForm.enterpriseId });
    if (res.businessCode === '0000') {
      setName(enterprise.label);
      setAddVisible(true);
    }
  };
  // 搜索
  const onFinish = async values => {
    setSearchForm(values);
    const pageInfo = {
      page: 1,
      size: 10,
    };
    setPage(pageInfo);
    shopList({ data: values, ...pageInfo });
  };
  // 重置
  const onReset = () => {
    formRef.current.resetFields();
    const pageInfo = {
      page: 1,
      size: 10,
    };
    setPage(pageInfo);
    setSearchForm({ enterpriseId: firstEnterprise });
    shopList({ data: { enterpriseId: firstEnterprise }, ...pageInfo });
  };
  // 分页
  const handleTableChange = (pageNo, size) => {
    const pageInfo = {
      page: pageNo,
      size,
    };
    setPage(pageInfo);
    shopList({ data: searchForm, ...pageInfo });
  };

  const pagination = {
    ...page,
    total,
    showTotal: t => `共 ${t} 条`,
    onChange: handleTableChange,
    onShowSizeChange: handleTableChange,
  };

  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
                    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>
      <Card>
        <Table
          columns={columns(res)}
          dataSource={dataList}
          rowKey={r => r.id}
          bordered
          pagination={pagination}
        />
      </Card>
      <EditRepastModal
        editVisible={editVisible}
        repastType={repastType}
        id={repastId}
        onCancel={closeModal}
        enterpriseId={searchForm.enterpriseId}
        isStore={isStore}
      />
      <AddModal
        addVisible={addVisible}
        enterpriseId={searchForm.enterpriseId}
        name={name}
        onCancel={closeModal}
      />
    </PageHeaderWrapper>
  );
};
export default StoreManagement;
