import { useEffect, useState } from 'react';
import { Button, Cascader, Form, Input, message, Modal, Select } from 'antd';
import { ArrowLeftOutlined, PlusOutlined, SaveOutlined } from '@ant-design/icons';
import SearchBox from '~/components/search-box';
import { useLocation, useNavigate } from 'react-router-dom';
import { InterDataType, InterListType, InterReqType } from '~/api/interface';
import { getCompanyInspectionByIdType } from '~/api/interface/mallManageType';
import { Uploader } from '~/components/uploader';
import { commonPriceValidator } from '~/utils/validateUtils';
import { CategoryManageAPI, MallManageAPI } from '~/api';
import RichText from '~/components/richText';
import DistrictJson from '~/assets/json/district.json';
import { useSelector } from 'react-redux';
import qs from 'query-string';
import { industryListPagesType } from '~/api/interface/categoryManage';

// 表单类型
type ReqType = InterReqType<getCompanyInspectionByIdType>;

function ServiceDetailView() {
  // 路由钩子
  const location = useLocation();
  // 导航钩子
  const navigate = useNavigate();
  // 返回上一页
  const handleBack = () => {
    navigate(-1);
    // Modal.confirm({
    //   title: '提示',
    //   content: '请确认是否保存？未保存的数据返回后将丢失',
    //   okText: '返回',
    //   cancelText: '取消',
    //   onOk: () => {
    //     navigate(-1);
    //   },
    // });
  };
  // 用户信息
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  // 表格数据类型
  const [form] = Form.useForm<ReqType>();
  // 地区列表
  const [districtList, setDistrictList] = useState<{ value: string; label: string }[]>();
  // 价格单位列表
  const [priceUnitList, setPriceUnitList] = useState<{ value: number; label: string }[]>();
  // 原始数据
  const [industryOriginList, setIndustryOriginList] =
    useState<InterListType<industryListPagesType>>();
  // 行业应用列表
  const [industryList, setIndustryList] = useState<
    { label: string; value: number; children: { label: string; value: number }[] }[]
  >([]);
  // 获取价格单位列表
  const getUnitList = async () => {
    const res = await MallManageAPI.listInspectionPriceUnit();
    if (res && res.code === '200') {
      setPriceUnitList(res.result?.map((i) => ({ label: i.unitName, value: i.id })) || []);
    }
  };
  // 获取地区列表
  const getDistrictList = () => {
    const list = DistrictJson.map((i) => ({
      label: i.name,
      value: String(i.id),
    }));
    setDistrictList(list || []);
  };
  // 获取行业列表
  const getIndustryList = async () => {
    const res = await CategoryManageAPI.industryListPages({
      pageNo: 1,
      pageSize: 9999,
    });
    if (res && res.code === '200') {
      const list = res.result?.list || [];
      setIndustryList(
        list.map((i) => ({
          label: i.typeName,
          value: i.id,
          children: i.inspectionDTOS?.map((j) => {
            return {
              label: j.inspectionName,
              value: j.id,
            };
          }),
        })),
      );
      setIndustryOriginList(list);
    }
  };
  // 上传图片
  const handleUpload = ({
    fileList,
    name,
    type,
    file,
  }: {
    fileList: { url: string }[];
    name: string;
    type: number;
    file: number;
  }) => {
    form.setFieldValue(
      name,
      fileList.map((i) => ({
        fileType: file,
        fileUrl: i.url,
        first: type,
        companyInspectionId: location.search ? Number(qs.parse(location.search).id) : undefined,
      })),
    );
    // console.log('上传图片 --->', list);
  };
  // 获取默认图片列表
  const getDefaultFileList = ({ name }: { name: string }) => {
    return (
      form.getFieldValue(name)?.map((i: { fileUrl: string }) => ({
        url: i.fileUrl,
      })) || []
    );
  };
  // 所属服务id
  const [inspectionId, setInspectionId] = useState<number>();
  // 服务标签列表
  const [inspectionTagList, setInspectionTagList] = useState<{ label: string; value: number }[]>();
  // 获取服务标签列表
  const getInspectionTagList = async () => {
    const res = await CategoryManageAPI.listByInspectionId({
      id: Number(inspectionId),
    });
    if (res && res.code === '200') {
      setInspectionTagList(res.result?.map((i) => ({ label: i.tagName, value: i.id })) || []);
      // console.log(res.result);
    }
  };
  // 表单提交
  const handleValid = () => {
    form
      .validateFields()
      .then((values) => {
        Modal.confirm({
          title: '提示',
          content: '请确认信息是否填写完成？',
          onOk: async () => {
            await handleSubmit(values);
          },
        });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: any) => {
    const id = Number(qs.parse(location.search).id);
    const res = await MallManageAPI[id ? 'companyInspectionUpdate' : 'companyInspectionInsert']({
      ...values,
      companyInspectionFiles: [
        ...(values.companyInspectionFiles1 || []),
        ...(values.companyInspectionFiles2 || []),
        ...(values.companyInspectionFiles3 || []),
      ],
      inspectionId: values.inspectionId.at(-1),
      companyInfoId: userInfo.companyInfoVO.id,
      serviceArea: values.serviceArea?.join(','),
      saleState: id ? serviceDetail?.saleState : 1,
      id: id || undefined,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleBack();
    }
  };
  // 服务详情
  const [serviceDetail, setServiceDetail] = useState<InterDataType<getCompanyInspectionByIdType>>();
  // 当前编辑的服务详情
  const getCompanyInspectionById = async ({ id }: { id: number }) => {
    const res = await MallManageAPI.getCompanyInspectionById({
      id,
    });
    if (res && res.code === '200') {
      setServiceDetail(res.result);
      setInspectionId(res.result.inspectionId);
      form.setFieldsValue({
        ...res.result,
        companyInspectionFiles1: res.result.inspectionFileDTOS.filter((i) => i.first === 1),
        companyInspectionFiles2: res.result.inspectionFileDTOS.filter(
          (i) => i.first === 0 && i.fileType === 0,
        ),
        companyInspectionFiles3: res.result.inspectionFileDTOS.filter((i) => i.fileType === 1),
        serviceArea: res.result.serviceArea?.split(','),
      });
    }
  };
  // 获取子分类的父分类id
  const getParentId = () => {
    if (!location.search) return;
    const list = industryOriginList?.map((i) => i.inspectionDTOS).flat() || [];
    const item = list.find((i) => i?.id === serviceDetail?.inspectionId);
    form.setFieldValue('inspectionId', [item?.industryTypeId, item?.id]);
  };
  // 组件挂载
  useEffect(() => {
    getDistrictList();
    getUnitList().then();
    getIndustryList().then();
    if (!location.search) return;
    getCompanyInspectionById({ id: Number(qs.parse(location.search)?.id) }).then();
    // console.log('用户信息 --->', qs.parse(location.search));
  }, []);
  // 监听服务id
  useEffect(() => {
    if (!inspectionId) return;
    console.log('执行到此处 --->', inspectionId);
    getInspectionTagList().then();
  }, [inspectionId]);
  // 监听行业列表
  useEffect(() => {
    if (!industryOriginList || industryOriginList.length === 0) return;
    getParentId();
  }, [industryOriginList]);
  return (
    <>
      <SearchBox
        preFixBtn={
          <div
            style={{
              width: '100%',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <div style={{ fontSize: '16px', fontWeight: 'bold' }}>新增服务</div>
            <div>
              <Button type={'primary'} icon={<SaveOutlined />} onClick={() => handleValid()}>
                保存
              </Button>
              <Button type={'default'} icon={<ArrowLeftOutlined />} onClick={() => handleBack()}>
                返回
              </Button>
            </div>
          </div>
        }
      />
      <Form form={form} labelAlign='right' labelCol={{ span: 3 }} wrapperCol={{ span: 10 }}>
        <Form.Item
          label='服务主图'
          name='companyInspectionFiles1'
          rules={[{ required: true, message: '请上传服务主图' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) =>
              handleUpload({ fileList: e, name: 'companyInspectionFiles1', type: 1, file: 0 })
            }
            defaultFileList={getDefaultFileList({ name: 'companyInspectionFiles1' })}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='服务副图'
          name='companyInspectionFiles2'
          rules={[{ required: false, message: '请上传服务副图' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={5}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) =>
              handleUpload({ fileList: e, name: 'companyInspectionFiles2', type: 0, file: 0 })
            }
            defaultFileList={getDefaultFileList({ name: 'companyInspectionFiles2' })}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='服务视频'
          name='companyInspectionFiles3'
          rules={[{ required: false, message: '请上传服务视频' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={500}
            fileType={['video/mp4', 'video/wmv', 'video/avi', 'video/mov', 'video/flv']}
            onChange={(e) =>
              handleUpload({ fileList: e, name: 'companyInspectionFiles3', type: 0, file: 1 })
            }
            defaultFileList={getDefaultFileList({ name: 'companyInspectionFiles3' })}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='服务地区'
          name='serviceArea'
          rules={[
            { required: true, message: '请选择服务地区' },
            // 最多只能选择5个地区
            () => ({
              validator(_, value) {
                if (value && value.length <= 5) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('最多只能选择5个地区'));
              },
            }),
          ]}
        >
          <Select
            placeholder={'请选择服务地区'}
            options={districtList}
            allowClear
            mode={'multiple'}
          />
        </Form.Item>
        <Form.Item
          label='所属服务'
          name='inspectionId'
          required
          rules={[
            // { required: true, message: '请选择所属服务' },
            () => ({
              validator(_, value) {
                if (value && value.length === 2) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('请选择所属服务'));
              },
            }),
          ]}
        >
          <Cascader
            placeholder={'请选择所属服务'}
            options={industryList}
            allowClear
            onChange={(e) => {
              form.setFieldValue('inspectionTagId', undefined);
              if (e.length === 2) setInspectionId(Number(e?.at(-1)));
            }}
          />
        </Form.Item>
        <Form.Item
          label='场景标签'
          name='inspectionTagId'
          rules={[{ required: false, message: '请选择场景标签' }]}
        >
          <Select placeholder={'请选择场景标签'} options={inspectionTagList} allowClear />
        </Form.Item>
        <Form.Item
          label='服务报价'
          name='price'
          rules={[{ required: true, validator: commonPriceValidator }]}
        >
          <Input placeholder='请输入服务报价' maxLength={15} allowClear type={'number'} />
        </Form.Item>
        <Form.Item
          label='报价说明'
          name='priceRemark'
          rules={[{ required: true, message: '请输入报价说明' }]}
        >
          <Input.TextArea placeholder='请输入报价说明' maxLength={50} allowClear showCount />
        </Form.Item>
        <Form.Item
          label='价格单位'
          name='inspectionPriceUnitId'
          rules={[{ required: true, message: '请选择价格单位' }]}
        >
          <Select placeholder={'请选择价格单位'} options={priceUnitList} allowClear />
        </Form.Item>
        <Form.Item label='备注' name='remark' rules={[{ required: false, message: '请输入备注' }]}>
          <Input.TextArea placeholder='请输入备注' maxLength={50} allowClear showCount />
        </Form.Item>
        <Form.Item
          label='详情页'
          name='detailPage'
          rules={[{ required: true, message: '请输入详情页' }]}
          wrapperCol={{ span: 20 }}
        >
          <RichText
            richTextContent={form.getFieldValue('detailPage')}
            onChange={(e) => form.setFieldValue('detailPage', e)}
            height={250}
          />
        </Form.Item>
      </Form>
    </>
  );
}

export default ServiceDetailView;
