/*
 * compName     : 基本设置组件
 * Description  :
 * Author       : 黎永顺
 * Date         : 2021-11-05 11:44:25
 * LastEditors: Please set LastEditors
 * LastEditTime: 2022-05-18 16:06:59
 */
import React, { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Upload,
  Form,
  Space,
  Radio,
  DatePicker,
  Select,
  message,
  Spin,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import API from '@/api';
import moment from 'moment';
import config from '@/config';
import { Session } from '@/utils';
import { Common } from '@/utils';
import styles from './index.less';

const token = Session.getAccessToken();
const headers = {
  Authorization: `Bearer ${token}`,
};
const { Option } = Select;

const AvatarView = ({
  avatar,
  onChange,
}: {
  avatar: string;
  onChange: Function;
}) => {
  const [iconUrl, setIconUrl] = useState(avatar || '');

  /**
   * 图片上传前校验
   */
  const beforeUpload = (file: any) => {
    const { name } = file;
    // 1. 上传文件提示
    if (_.isNil(name)) {
      message.error('请上传文件');
    }
    // 文件类型校验
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!(isJPG || isPNG)) {
      message.error('只能上传JPG 、PNG格式的图片~');
    }
    // 3. 文件大小校验
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('超过2M限制，不允许上传~');
    }
    return (isJPG || isPNG) && isLt2M;
  };

  const getBase64 = (img: any, callback: (imageUrl: any) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  /**
   * 文件上传后处理
   * @param info
   */
  const handleChange = async (info: any) => {
    let avatarObj: Record<string, string> = {
      avatar: '',
    };
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl: any) =>
        setIconUrl(imageUrl),
      );
      const response = info?.file?.response || {};
      if (!_.isEmpty(response)) {
        const { data } = response;
        avatarObj.avatar = data.id;
      }
      onChange && onChange(avatarObj);
    }
  };

  return (
    <>
      <div className={styles.avatar_title}>头像</div>
      <div className={styles.avatar}>
        <img src={avatar || iconUrl} alt="avatar" />
      </div>
      <Upload
        showUploadList={false}
        headers={headers}
        action={Common.uploadURLReturnDetail()}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        accept={config.get('picSuffix')}
      >
        <div className={styles.button_view}>
          <Button>
            <UploadOutlined />
            更换头像
          </Button>
        </div>
      </Upload>
    </>
  );
};

const Base: React.FC = () => {
  const [country, setCountry] = useState<Array<any>>([]);
  const [province, setProvince] = useState<Array<any>>([]);
  const [city, setCity] = useState<Array<any>>([]);
  const [currentUser, setCurrentUser] = useState<Record<string, any>>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  useEffect(() => {
    countryType();
    getCommonUserInfoByUserNo();
    return () => { };
  }, []);

  const getAvatarURL = () => {
    if (currentUser) {
      if (currentUser.avatar) {
        return Common.viewImg(currentUser.avatar);
      }
      const url =
        'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      return url;
    }
    return '';
  };

  /**
   * 获取地区信息
   */
  const countryType = () => {
    API.DictionaryService.countryType().then(({ success, data }) => {
      if (success && !_.isEmpty(data)) {
        setCountry(
          _.map(data, (it) => {
            return {
              label: it.name,
              value: it.code,
            };
          }),
        );
      }
    });
  };

  /**
   * 获取人员信息
   */
  const getCommonUserInfoByUserNo = () => {
    const { userNo } = Session.get();
    setLoading(true);
    API.AccountService.getCommonUserInfoByUserNo(userNo).then(
      ({ success, data }) => {
        setLoading(false);
        if (success && !_.isEmpty(data)) {
          const { birthday, avatar, country, province, city, ...datas } = data;
          setCurrentUser(data);
          country && handleCountryChange(country.split('|')[0]);
          province && handleProvinceChange(province.split('|')[0]);
          form.setFieldsValue({
            birthday: birthday ? moment(birthday) : void 0,
            country: country
              ? { label: country.split('|')[1], value: country.split('|')[0] }
              : undefined,
            province: province
              ? { label: province.split('|')[1], value: province.split('|')[0] }
              : undefined,
            city: city
              ? { label: city.split('|')[1], value: city.split('|')[0] }
              : undefined,
            ...datas,
          });
        }
      },
    );
  };

  const handleFinish = async (values: any) => {
    const { id } = Session.get();
    let { birthday, country, province, city, ...value } = values;
    birthday = moment(birthday).format('YYYY-MM-DD');
    const payload = {
      ...currentUser,
      birthday,
      country: `${country.value}|${country.label}`,
      province: `${province.value}|${province.label}`,
      city: `${city.value}|${city.label}`,
      ...value,
      id,
    };
    API.AccountService.updateUserInfo(payload).then(({ success }) => {
      if (success) {
        message.success('更新基本信息成功');
        getCommonUserInfoByUserNo();
      }
    });
  };

  const onReset = () => {
    form.resetFields();
    setProvince([]);
    setCity([]);
  };

  /**
   * 获取省级数据
   * @param code
   */
  const handleCountryChange = (code: string) => {
    setProvince([]);
    setCity([]);
    form.setFieldsValue({
      province: undefined,
      city: undefined,
    });
    API.DictionaryService.getChildDictionaryModelByParentId(code).then(
      ({ success, data }) => {
        if (success && !_.isEmpty(data)) {
          setProvince(
            _.map(data, (it) => {
              return {
                label: it.name,
                value: it.code,
              };
            }),
          );
        }
      },
    );
  };

  /**
   * 手机号认证
   * @param rule
   * @param value
   * @param callback
   */
  const validatorPhone = (
    rule: any,
    value: string,
    callback: (message?: string) => void,
  ) => {
    const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!reg.test(value)) {
      callback('请输入正确的手机号码!');
    }
    callback();
  };

  /**
   * 身份证号认证
   * @param rule
   * @param value
   * @param callback
   */
  const validatorIDCard = (
    rule: any,
    value: string,
    callback: (message?: string) => void,
  ) => {
    const reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
    if (!reg.test(value)) {
      callback('请输入正确的身份证号码!');
    }
    callback();
  };

  /**
   * 获取市级数据
   * @param code
   */
  const handleProvinceChange = (code: string) => {
    API.DictionaryService.getChildDictionaryModelByParentId(code).then(
      ({ success, data }) => {
        if (success && !_.isEmpty(data)) {
          setCity(
            _.map(data, (it) => {
              return {
                label: it.name,
                value: it.code,
              };
            }),
          );
        }
      },
    );
  };

  const handleAvatarChange = (avatar: any) => {
    setCurrentUser({ ...currentUser, ...avatar });
  };

  return (
    <div className={styles.baseView}>
      <div className={styles.left}>
        <Spin spinning={loading}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleFinish}
            autoComplete="off"
          >
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                {
                  type: 'email',
                  message: '请输入正确的邮箱地址!',
                },
              ]}
            >
              <Input placeholder="请输入" allowClear />
            </Form.Item>
            <Form.Item name="nickname" label="昵称">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
            <Form.Item
              name="idCard"
              label="身份证号"
              rules={[
                {
                  validator: validatorIDCard,
                },
              ]}
            >
              <Input placeholder="请输入" allowClear />
            </Form.Item>
            <Form.Item
              name="mobile"
              label="移动电话"
              rules={[
                {
                  validator: validatorPhone,
                },
              ]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item name="birthday" label="生日">
              <DatePicker
                style={{ width: '100%' }}
                getPopupContainer={(triggerNode: any) =>
                  triggerNode.parentElement
                }
              />
            </Form.Item>
            <Form.Item name="sex" label="性别">
              <Radio.Group buttonStyle="solid">
                <Radio.Button value="M">男</Radio.Button>
                <Radio.Button value="F">女</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item name="country" label="国家/地区">
              <Select
                allowClear
                style={{ width: '216px' }}
                showSearch
                getPopupContainer={(triggerNode) => triggerNode.parentElement}
                filterOption={(input, option: any) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
                labelInValue
                onChange={({ value }) => handleCountryChange(value)}
                onClear={() => {
                  setProvince([]);
                  setCity([]);
                }}
              >
                {country.map((it) => (
                  <Option key={it.value} value={it.value}>
                    {it.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="所在省市">
              <Form.Item
                name="province"
                style={{ display: 'inline-block', marginBottom: 0 }}
              >
                <Select
                  allowClear
                  showSearch
                  style={{ width: '216px', marginRight: 10 }}
                  disabled={_.isEmpty(province)}
                  getPopupContainer={(triggerNode) => triggerNode.parentElement}
                  filterOption={(input, option: any) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  labelInValue
                  onChange={({ value }) => handleProvinceChange(value)}
                  onClear={() => setCity([])}
                >
                  {province.map((it) => (
                    <Option key={it.value} value={it.value}>
                      {it.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                name="city"
                style={{ display: 'inline-block', marginBottom: 0 }}
              >
                <Select
                  allowClear
                  showSearch
                  disabled={_.isEmpty(city)}
                  getPopupContainer={(triggerNode) => triggerNode.parentElement}
                  style={{ width: '216px' }}
                  filterOption={(input, option: any) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  labelInValue
                >
                  {city.map((it) => (
                    <Option key={it.value} value={it.value}>
                      {it.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Form.Item>
            <Form.Item name="area" label="街道地址">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Spin>
      </div>
      <div className={styles.right}>
        <AvatarView avatar={getAvatarURL()} onChange={handleAvatarChange} />
      </div>
    </div>
  );
};

export default Base;
