import React, { useEffect, useState } from 'react';
import { getCompanyInfoByIdType } from '~/api/interface/systemManageType';
import { InterDataType, InterReqType } from '~/api/interface';
import SelectMapModal from '~/components/select-map';
import { Button, Form, Input, Modal, message } from 'antd';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { editUserApplyTag } from '~/api/interface/customManageType';
import { useNavigate } from 'react-router-dom';
import { CustomManageAPI } from '~/api';

// 店铺类型
type StoreType = InterDataType<getCompanyInfoByIdType>;
// 请求的表单类型
type ReqType = InterReqType<editUserApplyTag>;

const StoreFormView: React.FC<{
  detail: StoreType;
  onRefresh?: () => void;
}> = ({ detail, onRefresh }) => {
  // 导航钩子
  const navigate = useNavigate();
  // 表单数据
  const [form] = Form.useForm<ReqType>();
  // 是否选择地址弹窗
  const [openAddress, setOpenAddress] = useState<boolean>(false);
  // 选择的地址
  const [address, setAddress] = useState<{ lat: number; lon: number; address: string }>();
  // 品牌logo文件
  const [logoFileList, setLogoFileList] = useState<any>([]);
  // 品牌logo更换
  const brandLogoChange = (value: any) => {
    setLogoFileList(value);
    form.setFieldValue('brandLogo', value[0].url);
  };
  // 店铺图片列表
  const [imageList, setImageList] = useState<any>([]);
  // 店铺图片列表上传
  const imageListChange = (value: any) => {
    setImageList(value);
  };
  // 店铺视频列表
  const [videoList, setVideoList] = useState<any>([]);
  // 店铺视频列表上传
  const videoListChange = (value: any) => {
    setVideoList(value);
  };
  // 返回上一级
  const handleBack = () => {
    Modal.confirm({
      title: '提示',
      content: '未保存的内容将丢失，是否确认返回？',
      onOk: () => {
        navigate(-1);
      },
    });
  };
  // 表单验证
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: ReqType) => {
    const profileUrl = [
      ...(imageList?.map((i: { url: string }) => ({ url: i.url, type: 1 })) || []),
      ...(videoList?.map((i: { url: string }) => ({ url: i.url, type: 2 })) || []),
    ];
    const res = await CustomManageAPI.editUserApplyTag({
      companyInfoId: detail?.id,
      ...detail,
      ...address,
      ...values,
      profileUrl: JSON.stringify(profileUrl || []),
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      onRefresh?.();
    }
  };
  // 获取图片视频回显
  const getImageVideo = () => {
    try {
      const profileUrl = JSON.parse(detail?.profileUrl || `[]`);
      setImageList(
        profileUrl
          ?.filter((i: { type: number }) => i.type === 1)
          ?.map((i: { url: string }) => ({
            url: i?.url,
          })),
      );
      setVideoList(
        profileUrl
          ?.filter((i: { type: number }) => i.type === 2)
          ?.map((i: { url: string }) => ({
            url: i?.url,
          })),
      );
    } catch (e) {
      console.log(e);
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!detail?.id) return;
    form.setFieldsValue({
      ...detail,
      content: detail?.content || '航拍航测',
      address: detail?.address,
      name: detail?.companyName,
      attachmentList: detail?.attachmentList,
    });
    setLogoFileList([
      {
        id: Math.random(),
        uid: Math.random().toString(),
        name: 'brandLogo',
        url: detail?.brandLogo,
      },
    ]);
    getImageVideo();
  }, []);
  return (
    <>
      <div className={'store-title flex-between'}>
        <div className='title'>店铺页面</div>
        <div className='action flex-between'>
          <Button type={'primary'} onClick={handleOk}>
            保存
          </Button>
          <Button onClick={handleBack}>返回</Button>
        </div>
      </div>
      <Form form={form} labelCol={{ span: 3 }}>
        <Form.Item
          label='企业名称'
          name='name'
          rules={[{ required: true, message: '请输入企业名称' }]}
        >
          <Input placeholder={'请输入企业名称'} maxLength={25} allowClear />
        </Form.Item>
        <Form.Item
          label='网点地址'
          name='address'
          rules={[{ required: true, message: '请选择网点地址' }]}
        >
          <Input
            value={detail?.address}
            placeholder='请选择网点地址'
            maxLength={50}
            allowClear
            style={{ width: '300px', marginRight: '20px' }}
          />
          <Button
            type='primary'
            onClick={() => {
              setOpenAddress(true);
            }}
          >
            选择位置
          </Button>
        </Form.Item>
        <Form.Item label='店铺图片' name='imageList'>
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={imageList}
            onChange={imageListChange}
            fileLength={6}
            fileSize={50}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='店铺视频' name='videoList'>
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={videoList}
            onChange={videoListChange}
            fileLength={1}
            fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
            fileSize={100}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='服务资质'
          name='content'
          rules={[{ required: true, message: '请输入服务资质' }]}
        >
          <Input.TextArea
            placeholder={'请输入服务资质（“；”号换行）'}
            maxLength={140}
            allowClear
            showCount
          />
        </Form.Item>
        <Form.Item label='品牌logo' name='brandLogo'>
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={logoFileList}
            onChange={brandLogoChange}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        {/*<Form.Item label='营业执照'>*/}
        {/*  <Image src={detail?.licenseImg} width={45} height={45} />*/}
        {/*</Form.Item>*/}
        <Form.Item label='备注' name='remark'>
          <Input.TextArea placeholder='请输入备注' maxLength={70} showCount rows={4} />
        </Form.Item>
      </Form>
      <SelectMapModal
        title='选择位置'
        open={openAddress}
        closed={() => {
          setOpenAddress(false);
        }}
        submit={(e: { lat: number; lon: number; address: string }) => {
          form.setFieldValue('address', e.address);
          setAddress(e);
          setOpenAddress(false);
        }}
      />
    </>
  );
};

export default StoreFormView;
