import React, { useState, useRef, useEffect } from 'react';
import { notification, Button, Form, Input, Cascader, Col, Row, Table, Pagination } from 'antd';
import _ from 'lodash';
import { searchList, apiEnableStore, apiAddrArea } from './services';
import { stateDesc, weeks, layout } from './data';
import StoreModal from './components/storeModal';
import style from './style.less';

export default () => {
  const [visible, setVisible] = useState(false);
  const [storeInfo, setStoreInfo] = useState({});
  const [areaAddr, setAreaAddr] = useState([]);
  const [dataList, setDataList] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [totalNum, setTotalNum] = useState(0);
  const [pageSize, setPageSize] = useState(20);
  const refSearch = useRef();
  const divDom = useRef();
  const onCreate = () => {
    setStoreInfo({});
    setVisible(true);
  };
  const onShowInfo = info => {
    setStoreInfo(info);
    setVisible(true);
  };

  // 获取市区街道
  const loadData = async selectedOptions => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const res = await apiAddrArea({
      parentId: targetOption.value,
    });
    if (res) {
      const children = res.map(item => ({
        isLeaf: +item.addrLevel === 4,
        loading: false,
        label: item.addrName,
        value: item.addrId,
      }));
      targetOption.loading = false;
      if (children.length > 0) {
        targetOption.children = children;
      } else {
        targetOption.isLeaf = true;
        if (selectedOptions.length === 3) {
          divDom.current.blur();
        }
      }
      setAreaAddr([...areaAddr]);
    }
  };
  const getAreaAddr = async id => {
    const params = {};
    if (id) {
      params.parentId = id;
    }
    const res = await apiAddrArea(params);
    if (res) {
      const arr = res.map(item => ({
        isLeaf: false,
        loading: false,
        label: item.addrName,
        value: item.addrId,
      }));
      setAreaAddr(arr);
      return arr;
    }
    return [];
  };

  const getList = async (params = {}) => {
    const res = await searchList(Object.assign({ current: pageNo, pageSize }, params));
    if (res && res.data && res.data.length) {
      setDataList(res.data);
    } else {
      setDataList([]);
    }
    setTotalNum(res.total);
  };

  // 搜索
  const onSearch = async val => {
    const params = {};
    if (val.name) {
      params.name = val.name;
    }
    if (val.addr && val.addr.length) {
      const ids = ['provinceId', 'cityId', 'countyId', 'townId'];
      val.addr.forEach((item, i) => {
        params[ids[i]] = item;
      });
    }
    getList(params);
  };
  const closeModal = isReload => {
    if (isReload) {
      onSearch(refSearch.current?.getFieldValue?.() || {});
    }
    setStoreInfo({});
    setVisible(false);
  };
  const onEnableState = async ({ id, state }) => {
    const enable = +state === 1 ? 0 : 1;
    const res = await apiEnableStore({ id, state: enable });
    if (res === '0000') {
      notification.success({ message: `已${state ? '禁用' : '启用'}` });
      onSearch(refSearch.current?.getFieldValue?.() || {});
    }
  };

  const onReset = () => {
    if (refSearch.current && refSearch.current.resetFields) {
      refSearch.current.resetFields();
    }
  };

  const onPageChange = (e, size) => {
    setPageNo(e);
    setPageSize(size);
    onSearch(refSearch.current?.getFieldValue?.() || {});
  };

  useEffect(() => {
    getList();
    getAreaAddr();
  }, []);

  const getWeekSlots = weekArr => {
    const htmlArr = [];
    if (weekArr && weekArr.length) {
      const arr = [];
      let brr = [];
      weekArr.reduce((prev, cur) => {
        if (prev + 1 === cur) {
          brr.push(cur);
        } else {
          arr.push(brr);
          brr = [cur];
        }
        return cur;
      }, 0);
      arr.push(brr);
      if (arr.length) {
        arr.forEach(item => {
          if (htmlArr.length) {
            htmlArr.push(',');
          }
          if (item.length > 1) {
            htmlArr.push(
              <span key={item[0]}>
                {weeks[item[0]]} ~ {weeks[item[item.length - 1]]}
              </span>,
            );
          } else {
            htmlArr.push(<span key={item[0]}>{weeks[item[0]]}</span>);
          }
        });
      }
    }
    return htmlArr;
  };

  const columns = [
    {
      title: '门店名称',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '门店电话',
      dataIndex: 'phone',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '营业时间',
      dataIndex: 'businessHours',
      hideInSearch: true,
      width: 150,
      render: businessHours => (
        <div>
          <div>{getWeekSlots(businessHours.weeks)}</div>
          <div>
            {businessHours.hoursItems.map(item => (
              <div key={item.begin}>
                <span>{item.begin}</span>-<span>{item.end}</span>
              </div>
            ))}
          </div>
        </div>
      ),
    },
    {
      title: '地区',
      dataIndex: 'addr',
      width: 200,
      hideInSearch: true,
      render: (addr, r) => (
        <span>{`${r.provinceName}${r.cityName}${r.countyName}${r.townName || ''}`}</span>
      ),
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      hideInSearch: true,
      width: 150,
    },
    {
      title: '经纬度',
      dataIndex: 'latlng',
      hideInSearch: true,
      width: 120,
      render: (latlng, r) => <span>{`${r.longitude},${r.latitude}`}</span>,
    },
    {
      title: '状态',
      dataIndex: 'state',
      hideInSearch: true,
      width: 120,
      render: v => <span>{`${stateDesc[v]}`}</span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      hideInSearch: true,
      width: 120,
    },
    {
      title: '操作',
      hideInSearch: true,
      dataIndex: 'action',
      width: 170,
      fixed: 'right',
      render: (val, r) => [
        <Button key="enable1" onClick={() => onEnableState(r)} type="primary">
          {+r.state ? '禁用' : '启用'}
        </Button>,
        <Button key="seek" style={{ marginLeft: '10px' }} onClick={() => onShowInfo(r)}>
          查看
        </Button>,
      ],
    },
  ];
  return (
    <div>
      <div className={style.serachForm}>
        <Form {...layout} ref={refSearch} onFinish={e => onSearch(e)} name="formData">
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="门店名称" name="name">
                <Input placeholder="请输入门店名称" allowClear maxLength={20} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="地区" name="addr">
                <Cascader
                  ref={divDom}
                  options={areaAddr}
                  loadData={e => loadData(e)}
                  changeOnSelect
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Button type="primary" htmlType="submit" size="middle">
                搜索
              </Button>
              <Button size="middle" className={style.searchBtn} onClick={() => onReset()}>
                重置
              </Button>
              <Button type="primary" size="middle" onClick={() => onCreate()}>
                新建
              </Button>
            </Col>
          </Row>
        </Form>
      </div>
      <Table
        dataSource={dataList}
        bordered
        columns={columns}
        rowKey={record => record.id}
        pagination={false}
        scroll={{ x: '100%' }}
      />
      {dataList && dataList.length && (
        <div className={style.pageBox}>
          <Pagination
            style={{ marginBottom: 10 }}
            onChange={onPageChange}
            total={totalNum}
            showTotal={total => `共${total}条`}
            current={pageNo}
            pageSize={pageSize}
            showSizeChanger
            onShowSizeChange={onPageChange}
          />
        </div>
      )}
      <StoreModal visible={visible} onCancel={closeModal} formInfo={storeInfo} />
    </div>
  );
};
