import React, { useState, useEffect, useRef } from 'react';
import { Form } from '@ant-design/compatible';
import moment from 'moment';
import { PlusSquareFilled, MinusSquareFilled } from '@ant-design/icons';
import { Modal, Input, TimePicker, Checkbox, Cascader, Radio, notification, Button } from 'antd';
import { apiAddrArea, apiCreatStore, apiEditStore } from '../services';
import { weekOptions, weekDefault, layout } from '../data';
import MapModal from '@/components/GaoDeMap';
import style from './style.less';
import { isCheckNumberLine } from '@/utils/validator';
import Upload from '../../components/upload';

const FormItem = Form.Item;

const StoreModal = props => {
  const {
    visible,
    onCancel,
    form: { getFieldDecorator, setFieldsValue, getFieldsValue, validateFields, resetFields },
    formInfo,
    status,
    productBusiness,
    existTakewayShop,
  } = props;
  const [areaAddr, setAreaAddr] = useState([]);
  const [visibleMap, setVisibleMap] = useState(false);
  const [times, setTimes] = useState([{ name: 'time0' }]);
  const [formData, setFormData] = useState({});
  const [mapInfo, setMapInfo] = useState({
    provice: '',
    address: '',
  });
  const [disabled, setDisabled] = useState(false);
  const [isDisabled, setIsDisabled] = useState(false);
  const [businessModel, setBusinessModel] = useState([
    { label: '到家外卖业务(外卖配送业务)', value: 1 },
    { label: '实物商品业务员', value: 2 },
    { label: '到店业务(服务类业务)', value: 3 },
  ]);
  const divDom = useRef();

  const handleCancel = isSuccess => {
    resetFields();
    onCancel(isSuccess);
  };

  const onSubmit = () => {
    validateFields(async (error, fieldsValue) => {
      if (!error) {
        const params = Object.assign({}, formInfo, fieldsValue);
        const areaArr = ['provinceId', 'cityId', 'countyId', 'townId'];
        if (params.addr && params.addr.forEach) {
          params.addr.forEach((item, i) => {
            params[areaArr[i]] = item;
          });
        }
        if (params?.shopHeadImage?.length) {
          // eslint-disable-next-line prefer-destructuring
          params.shopHeadImage = params.shopHeadImage[0];
        }
        if (params.lnglat) {
          const arr = params.lnglat.split(',');
          if (arr.length === 2) {
            params.longitude = arr[0] || '';
            params.latitude = arr[1] || '';
          }
        }
        const hoursItems = [];
        if (times && times.length && times.forEach) {
          times.forEach(item => {
            hoursItems.push({
              begin: moment(params[item.name][0]).format('HH:mm'),
              end: moment(params[item.name][1]).format('HH:mm'),
            });
          });
        }
        params.businessHours = {
          weeks: params.week,
          hoursItems,
        };
        let api = apiCreatStore;
        if (params.id) {
          api = apiEditStore;
        }
        const res = await api(params);
        if (res === '0000') {
          notification.success({ message: '保存成功' });
          handleCancel(true);
        }
      }
    });
  };

  const getAreas = arr => {
    let areas = areaAddr;
    let addr = '';
    arr.forEach(c => {
      let index = 0;
      areas.forEach((item, i) => {
        if (item.value === c) {
          addr += item.label;
          index = i;
        }
      });
      areas = areas[index].children;
    });
    return addr;
  };

  // 显示地图
  const openMap = v => {
    const values = getFieldsValue();
    let provice = '北京市';
    if (!values.addr) {
      notification.warning({ message: '请先选择店铺区域' });
      return;
    }

    if (!values.address) {
      notification.warning({ message: '请先填写完整的详细地址' });
      return;
    }
    if (values.addr.length > 0) {
      areaAddr.forEach(item => {
        if (item.value === values.addr[0]) {
          provice = item.label;
        }
      });
    }
    const labels = getAreas(values.addr);
    setMapInfo({
      provice,
      address: labels + values.address,
    });
    setVisibleMap(v);
  };

  // 获取地址省
  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 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 onTimePlus = () => {
    times.push({
      name: `time${times.length}`,
    });
    setTimes([...times]);
  };
  const onTimeMinus = i => {
    times.splice(i, 1);
    setTimes([...times]);
  };

  const onSetPoint = e => {
    setFieldsValue({
      lnglat: e,
    });
  };

  const getLazyAddr = async info => {
    const arr = await getAreaAddr();
    const parr = arr.filter(item => +item.value === +info.provinceId);
    parr[0].children = await getAreaAddr(parr[0].value);
    const carr = parr[0].children.filter(item => +item.value === +info.cityId);
    carr[0].children = await getAreaAddr(carr[0].value);
    if (info.townId) {
      const aarr = carr[0].children.filter(item => +item.value === +info.countyId);
      aarr[0].children = await getAreaAddr(aarr[0].value);
    }
    setAreaAddr([...arr]);
  };

  const normFile = fileList => fileList;

  const timerWrapper = async (time, timeString, callback) => {
    if (timeString && timeString.length) {
      const begin = moment(timeString[0]).format('HH:mm');
      const end = moment(timeString[1]).format('HH:mm');
      if (begin === end) {
        callback(new Error('选择开始时间结束时间不能一样'));
      }
    } else {
      callback();
    }
  };

  const onBusiness = e => {
    const val = e.includes(1);
    setIsDisabled(val);
  };
  useEffect(() => {
    if (visible) {
      resetFields();
      const info = Object.assign({}, formInfo);
      const val = info?.productBusiness?.includes(1);
      setIsDisabled(val);
      if (status === 'look') {
        setDisabled(true);
      } else {
        setDisabled(false);
      }
      const data = [...businessModel];
      data.forEach(item => {
        item.disabled = !productBusiness.includes(item.value);
        if (existTakewayShop && item.value === 1 && !val) {
          item.disabled = true;
        }
      });
      console.log(data, '.........');
      setBusinessModel(data);
      if (info && info.id) {
        info.week = info.businessHours.weeks;
        const hours = info.businessHours.hoursItems;
        const harr = [];
        if (hours && hours.length) {
          hours.forEach((item, i) => {
            info[`time${i}`] = [moment(item.begin, 'HH:mm'), moment(item.end, 'HH:mm')];
            harr.push({
              name: `time${i}`,
            });
          });
        }

        info.lnglat = `${info.longitude},${info.latitude}`;
        info.addr = [info.provinceId, info.cityId, info.countyId];
        info.shopHeadImage = (info.shopHeadImage && [info.shopHeadImage]) || [];
        if (info.townId) {
          info.addr.push(info.townId);
        }
        setTimes(harr);
        setFormData(info);
        getLazyAddr(info);
      } else {
        if (areaAddr.length < 1) {
          getAreaAddr();
        }
        setFormData({});
      }
    }
  }, [visible]);

  return (
    <Modal
      title="门店信息"
      visible={visible}
      width="1000px"
      destroyOnClose
      maskClosable={false}
      onCancel={() => handleCancel()}
      footer={
        <>
          <Button key="back" onClick={() => handleCancel()}>
            取消
          </Button>
          {!disabled && (
            <Button key="submit" type="primary" onClick={() => onSubmit()}>
              确定
            </Button>
          )}
        </>
      }
    >
      <Form {...layout} name="formData">
        <FormItem label="业务模式">
          {getFieldDecorator('productBusiness', {
            rules: [{ required: true, message: '请选择业务模式' }],
            initialValue: formData.productBusiness,
          })(<Checkbox.Group disabled={disabled} options={businessModel} onChange={onBusiness} />)}
        </FormItem>
        {isDisabled && (
          <FormItem label="门店头像">
            {getFieldDecorator('shopHeadImage', {
              rules: [{ required: true, message: '请上传门店头像' }],
              initialValue: formData.shopHeadImage || [],
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
            })(<Upload max={1} accept=".jpg,.png,.jpeg" disabled={disabled} />)}
          </FormItem>
        )}
        <FormItem
          label="门店名称"
          name="name"
          extra="门店名称由商家名称+门店地址组成，示例：优衣库（三里屯店）"
        >
          {getFieldDecorator('name', {
            rules: [{ required: true, message: '请输入门店名称!' }],
            initialValue: formData.name,
          })(<Input placeholder="请输入门店名称" allowClear maxLength={20} disabled={disabled} />)}
        </FormItem>
        <FormItem label="门店电话" name="phone">
          {getFieldDecorator('phone', {
            rules: [
              { required: true, message: '请输入门店电话!' },
              { validator: isCheckNumberLine, message: '请输入正确的门店电话!' },
            ],
            initialValue: formData.phone,
          })(<Input placeholder="请输入门店电话" allowClear maxLength={20} disabled={disabled} />)}
        </FormItem>
        <FormItem label="营业时间" required>
          {times &&
            times.map((item, i) => (
              <div className={style.timerWrapper} key={item.name}>
                <div>
                  <FormItem name={item.name}>
                    {getFieldDecorator(item.name, {
                      rules: [
                        { required: true, message: '请选择营业时间!' },
                        { validator: timerWrapper, message: '选择开始时间结束时间不能一样' },
                      ],
                      initialValue: formData[item.name],
                    })(<TimePicker.RangePicker format="HH:mm" disabled={disabled} />)}
                  </FormItem>
                </div>
                {!disabled &&
                  (i > 0 ? (
                    <div className={style.timerWrapperRight} onClick={() => onTimeMinus(i)}>
                      <MinusSquareFilled
                        style={{ color: '#ff4d4f', fontSize: '30px' }}
                        disabled={disabled}
                      />
                    </div>
                  ) : (
                    <div className={style.timerWrapperRight} onClick={() => onTimePlus()}>
                      <PlusSquareFilled
                        style={{ color: '#1890ff', fontSize: '30px' }}
                        disabled={disabled}
                      />
                    </div>
                  ))}
              </div>
            ))}
        </FormItem>
        <FormItem label="营业日">
          {getFieldDecorator('week', {
            rules: [{ required: true, message: '请选择营业日!' }],
            initialValue: formData.week || weekDefault,
          })(<Checkbox.Group options={weekOptions} disabled={disabled} />)}
        </FormItem>
        <FormItem label="店铺区域">
          {getFieldDecorator('addr', {
            rules: [{ required: true, type: 'array', message: '请选择店铺区域!' }],
            initialValue: formData.addr,
          })(
            <Cascader
              ref={divDom}
              options={areaAddr}
              placeholder="请选择店铺区域"
              loadData={e => loadData(e)}
              changeOnSelect
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label="详细地址">
          {getFieldDecorator('address', {
            rules: [{ required: true, message: '请输入详细地址!' }],
            initialValue: formData.address,
          })(
            <Input
              placeholder="请输入详细地址，不包含省市区地址"
              allowClear
              maxLength={50}
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label="经纬度">
          {getFieldDecorator('lnglat', {
            rules: [{ required: true, message: '请选择经纬度!' }],
            initialValue: formData.lnglat,
          })(
            <Input
              placeholder="请选择经纬度"
              readOnly
              onClick={() => openMap(true)}
              maxLength={100}
              disabled={disabled}
            />,
          )}
        </FormItem>
        <FormItem label="是否启用">
          {getFieldDecorator('state', {
            rules: [{ required: true, message: '请选择是否启用!' }],
            initialValue: formData.state,
          })(
            <Radio.Group disabled={disabled}>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>,
          )}
        </FormItem>
        {isDisabled && (
          <FormItem label="门店公告">
            {getFieldDecorator('publicNotice', {
              initialValue: formData.publicNotice,
            })(<Input placeholder="请输入门店公告" maxLength={120} disabled={disabled} />)}
          </FormItem>
        )}
      </Form>
      <MapModal
        visible={visibleMap}
        addrInfo={mapInfo}
        onCancel={() => openMap(false)}
        onSetPoint={e => onSetPoint(e)}
      ></MapModal>
    </Modal>
  );
};

export default Form.create()(StoreModal);
