import React, { useEffect, useState } from 'react';
import { getCompanyInfoByIdType } from '~/api/interface/systemManageType';
import { InterDataType, InterReqType } from '~/api/interface';
import { Button, Form, 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';
import RichText from '~/components/richText';

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

const StoreDescView: React.FC<{
  detail: StoreType;
  onRefresh?: () => void;
}> = ({ detail, onRefresh }) => {
  // 导航钩子
  const navigate = useNavigate();
  // 表单数据
  const [form] = Form.useForm<ReqType>();
  // 店铺视频列表
  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 = [
      ...(videoList?.map((i: { url: string }) => ({ url: i.url, type: 2 })) || []),
    ];
    const res = await CustomManageAPI.editUserApplyTag({
      companyInfoId: detail?.id,
      ...detail,
      ...values,
      profileUrl: JSON.stringify(profileUrl || []),
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      onRefresh?.();
    }
  };
  // 获取图片视频回显
  const getImageVideo = () => {
    try {
      const profileUrl = JSON.parse(detail?.profileUrl || `[]`);
      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,
    });
    getImageVideo();
  }, []);
  return (
    <div style={{ width: '880px', paddingTop: '20px' }}>
      <Form form={form} labelCol={{ span: 2 }}>
        <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', 'video/mov']}
            fileSize={100}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='企业介绍'
          name='profileText'
          rules={[{ required: false, message: '请输入企业介绍' }]}
        >
          <RichText
            richTextContent={form.getFieldValue('profileText')}
            onChange={(e) => form.setFieldValue('profileText', e)}
            height={250}
          />
        </Form.Item>
      </Form>
      <div className={'store-title flex-center'}>
        {/*<div className='title'>店铺页面</div>*/}
        <div className='action flex-between' style={{ width: '120px' }}>
          <Button type={'primary'} onClick={handleOk}>
            保存
          </Button>
          <Button onClick={handleBack}>返回</Button>
        </div>
      </div>
    </div>
  );
};

export default StoreDescView;
