import Constants from '@/constants';
import {
  adminChangeBusinessInfoUsingPost,
  getPbcBusinessByIdUsingPost,
} from '@/services/pop-b2b2c/pbcBusinessController';
import { getCities } from '@/utils/cities';
import { CheckCircleOutlined, InfoCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import {
  ProCard,
  ProConfigProvider,
  ProDescriptions,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { DndContext, DragEndEvent, PointerSensor, useSensor } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useAccess, useParams, useSearchParams } from '@umijs/max';
import { Button, Form, Image, message, Tag } from 'antd';
import { RcFile, UploadFile } from 'antd/es/upload';
import React, { useEffect, useState } from 'react';
import { CSS } from '@dnd-kit/utilities';

interface DraggableUploadListItemProps {
  originNode: React.ReactElement<any, string | React.JSXElementConstructor<any>>;
  file: UploadFile<any>;
}

const DraggableUploadListItem = ({ originNode, file }: DraggableUploadListItemProps) => {
  let { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: file.uid,
  });

  const style: React.CSSProperties = {
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      // prevent preview event when drag end
      className={isDragging ? 'is-dragging' : ''}
      {...attributes}
      {...listeners}
    >
      {/* hide error tooltip when dragging */}
      {file.status === 'error' && isDragging ? originNode.props.children : originNode}
    </div>
  );
};
const Detail: React.FC<any> = () => {
  const params = useParams();
  const [searchParams] = useSearchParams();
  const access: any = useAccess();
  const isEdit = searchParams.get('isEdit') === '1';
  const [cities] = useState(() => getCities())

  const [info, setInfo] = useState<API.PbcBusiness>({});
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();

  const getInfo = () => {
    if (params.id) {
      getPbcBusinessByIdUsingPost({ pbcId: parseInt(params.id) }).then((res) => {
        if (res.retcode && res.data) {
          setInfo(res.data);
        }
      });
    }
  };

  useEffect(() => {
    getInfo();
  }, []);

  const sensor = useSensor(PointerSensor, {
    activationConstraint: { distance: 10 },
  });

  const onDragEnd = ({ active, over }: DragEndEvent, fieldName: string, type: number) => {
    if (active.id !== over?.id) {
      const arr = type === 1 ? form1.getFieldValue(fieldName) || [] : form2.getFieldValue(fieldName)
      const activeIndex = arr.findIndex((i: any) => i.uid === active.id);
      const overIndex = arr.findIndex((i: any) => i.uid === over?.id);
      const newArr = arrayMove(arr, activeIndex, overIndex)
      if (type === 1) {
        form1.setFieldValue(fieldName, newArr)
      } else {
        form2.setFieldValue(fieldName, newArr)
      }
    }
  };

  return (
    <PageContainer
      header={{
        title: '',
      }}
      footer={[
        <Button
          key="back"
          onClick={() => {
            history.back();
          }}
        >
          返回
        </Button>,
      ]}
    >
      <ProCard style={{ marginBottom: 12 }}>
      <ProConfigProvider
          valueTypeMap={{
            upload: {
              render: (text) => {
                return text.length > 0 ? text.map((e: any) => 
                  <Image key={e.url} width={200} src={e.url}></Image>
                ) : (
                  <span></span>
                );
              },
              renderFormItem: (text, props: any) => {
                return (
                  <DndContext sensors={[sensor]} onDragEnd={(event) => onDragEnd(event, props.id, 1)}>
                    <SortableContext items={form1.getFieldValue(props.id) ? form1.getFieldValue(props.id).map((i: any) => i.uid) : []} strategy={verticalListSortingStrategy}>
                      <ProFormUploadButton
                        {...props}
                        {...props?.fieldProps}
                        icon={<PlusCircleOutlined style={{ fontSize: 30 }} />}
                        title={<div style={{ marginTop: 10, fontSize: 12 }}>点击上传图片</div>}
                        fieldProps={{
                          name: 'file',
                          accept: 'image/*',
                          multiple: true,
                          listType: 'picture-card',
                          headers: {
                            authorization: localStorage.getItem('token') ?? '',
                          },
                          itemRender: (originNode, file) => <DraggableUploadListItem originNode={originNode} file={file} />,
                          beforeUpload(file: RcFile) {
                            const isLt2M = file.size / 1024 / 1024 < 10;
                            if (!isLt2M) {
                              message.error('图片大小不能超过10MB!');
                            }
                            return isLt2M;
                          },
                          onPreview: async (file) => {
                            if (file.response && file.response.retcode) {
                              window.open(file.response.data);
                            } else {
                              window.open(file.url);
                            }
                          },
                        }}
                        action={process.env.BASE_URL + '/oss/imgUpload'}
                        onChange={(a: any) => {
                          props?.fieldProps.onChange(a.fileList);
                        }}
                      />
                    </SortableContext>
                  </DndContext>
                );
              },
            },
          }}
          hashed={false}
        >
          <ProDescriptions
            editable={
              access.businessSave && isEdit
                ? {
                    form: form1,
                    onSave: async (key, record: any, originRow) => {
                      let pbcState = record.pbcState;
                      let pbcBusinessLogo = "";
                      let pbcBusinessImage = [];
                      let pbcBusinessPosterUrl = [];
                      let pbcZone = ['', '', ''];
                      if (key === 'pbcState') {
                        pbcState = record[key] ? 1 : 2;
                      }
                      if (key === 'pbcZone' && record[key] && record[key].length > 0) {
                          pbcZone = record[key];
                      }
                      if (
                        key === 'pbcBusinessLogo' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        if (record[key][0].uid === '-1') {
                          pbcBusinessLogo = record[key][0].url;
                        }
                        if (record[key][0].response && record[key][0].response.retcode) {
                          pbcBusinessLogo = record[key][0].response.data;
                        }
                      }
                      if (
                        key === 'pbcBusinessImage' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        for (let i = 0; i < record[key].length; i++) {
                          const element = record[key][i];
                          if (element.response && element.response.retcode) {
                            pbcBusinessImage.push(element.response.data)
                          } else {
                            pbcBusinessImage.push(element.url)
                          }
                        }
                      }
                      if (
                        key === 'pbcBusinessPosterUrl' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        for (let i = 0; i < record[key].length; i++) {
                          const element = record[key][i];
                          if (element.response && element.response.retcode) {
                            pbcBusinessPosterUrl.push(element.response.data)
                          } else {
                            pbcBusinessPosterUrl.push(element.url)
                          }
                        }
                      }
                      await adminChangeBusinessInfoUsingPost({
                        ...info,
                        //@ts-ignore
                        [key]: record[key],
                        pbcState: key === 'pbcState' ? pbcState : info.pbcState,
                        pbcBusinessProvince: key === 'pbcZone' ? pbcZone[0] : info.pbcBusinessProvince,
                        pbcBusinessCity: key === 'pbcZone' ? pbcZone[1] : info.pbcBusinessCity,
                        pbcBusinessArea: key === 'pbcZone' ? pbcZone[2] : info.pbcBusinessArea,
                        pbcBusinessLogo: key === 'pbcBusinessLogo' ? pbcBusinessLogo : info.pbcBusinessLogo,
                        pbcBusinessImage: key === 'pbcBusinessImage' ? pbcBusinessImage.join(',') : info.pbcBusinessImage,
                        pbcBusinessPosterUrl: key === 'pbcBusinessPosterUrl' ? pbcBusinessPosterUrl.join(',') : info.pbcBusinessPosterUrl,
                      })
                        .then((res) => {
                          if (res.retcode) {
                            getInfo();
                            message.success('修改成功');
                            return record;
                          } else {
                            message.error('修改失败');
                            return originRow;
                          }
                        })
                        .catch(() => {
                          return originRow;
                        });
                    },
                  }
                : undefined
            }
            bordered
            title={
              <>
                <span style={{ marginRight: 20 }}>基本信息</span>
                {info.pbcBusinessState === 1 ? (
                  <Tag icon={<CheckCircleOutlined />} color="success">
                    已认证
                  </Tag>
                ) : (
                  <Tag icon={<InfoCircleOutlined />} color="default">
                    未认证
                  </Tag>
                )}
              </>
            }
            dataSource={{
              pbcBusinessName: info.pbcBusinessName,
              pbcBusinessType: info.pbcBusinessType,
              pbcState: info.pbcState,
              pbcBusinessContact: info.pbcBusinessContact,
              pbcBusinessContactMobile: info.pbcBusinessContactMobile,
              pbcBusinessLevel: info.pbcBusinessLevel,
              pbcBusinessEmail: info.pbcBusinessEmail,
              pbcBusinessIntroduction: info.pbcBusinessIntroduction,
              pbcBusinessAddress: info.pbcBusinessAddress,
              pbcBusinessDoorLabel: info.pbcBusinessDoorLabel,
              pbcZone: [info.pbcBusinessProvince, info.pbcBusinessCity, info.pbcBusinessArea],
              pbcBusinessLogo: info.pbcBusinessLogo ? [
                  {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: info.pbcBusinessLogo,
                  },
                ]
              : [],
              pbcBusinessImage:  info.pbcBusinessImage ? info.pbcBusinessImage.split(',').map((e, index) => {
                return {
                  uid: '-' + (index+1),
                  name: 'image.png',
                  status: 'done',
                  url: e,
                }
              }) : [],
              pbcBusinessPosterUrl: info.pbcBusinessPosterUrl ? info.pbcBusinessPosterUrl.split(',').map((e, index) => {
                return {
                  uid: '-' + (index+1),
                  name: 'image.png',
                  status: 'done',
                  url: e,
                }
              }) : [],
            }}
            columns={[
              {
                title: '商户名称',
                key: 'pbcBusinessName',
                dataIndex: 'pbcBusinessName',
              },
              {
                title: '商户类别',
                key: 'pbcBusinessType',
                dataIndex: 'pbcBusinessType',
                valueEnum: Constants.pbcBusinessType
              },
              {
                title: '商户状态',
                key: 'pbcState',
                dataIndex: 'pbcState',
                valueType: "switch",
                fieldProps:{ checkedChildren: '启用', unCheckedChildren: '禁用' }
              },
              {
                title: '联系人',
                key: 'pbcBusinessContact',
                dataIndex: 'pbcBusinessContact',
              },
              {
                title: '手机号',
                key: 'pbcBusinessContactMobile',
                dataIndex: 'pbcBusinessContactMobile',
              },
              {
                title: '商户等级',
                key: 'pbcBusinessLevel',
                dataIndex: 'pbcBusinessLevel',
                valueType: "select",
                fieldProps: { options: ['1级', '2级', '3级', '4级', '5级'] }
              },
              {
                title: '邮箱',
                key: 'pbcBusinessEmail',
                dataIndex: 'pbcBusinessEmail',
              },
              {
                title: '商户简介',
                key: 'pbcBusinessIntroduction',
                valueType: 'textarea',
                span: 2,
                dataIndex: 'pbcBusinessIntroduction'
              },
              {
                title: '省市区',
                key: 'pbcZone',
                valueType: 'cascader',
                fieldProps: { options: cities },
                dataIndex: 'pbcZone',
              },
              {
                title: '详细地址',
                key: 'pbcBusinessAddress',
                dataIndex: 'pbcBusinessAddress',
              },
              {
                title: '门牌号',
                key: 'pbcBusinessDoorLabel',
                dataIndex: 'pbcBusinessDoorLabel',
              },
              {
                title: '商户LOGO',
                key: 'pbcBusinessLogo',
                dataIndex: 'pbcBusinessLogo',
                span: 3,
                valueType: 'upload',
                fieldProps: {
                  max: 1
                }
              },
              {
                title: '商户图片',
                key: 'pbcBusinessImage',
                dataIndex: 'pbcBusinessImage',
                span: 3,
                valueType: 'upload',
              },
              {
                title: '商户海报',
                key: 'pbcBusinessPosterUrl',
                dataIndex: 'pbcBusinessPosterUrl',
                span: 3,
                valueType: 'upload',
              },
            ]}
            column={3}
          ></ProDescriptions>
        </ProConfigProvider>
      </ProCard>
      <ProCard style={{ marginBottom: 12 }}>
        <ProConfigProvider
          valueTypeMap={{
            upload: {
              render: (text) => {
                console.log(text)
                return text.length > 0 ? text.map((e: any) => 
                  <Image key={e.url} width={200} src={e.url}></Image>
                ) : (
                  <span></span>
                );
              },
              renderFormItem: (text, props: any) => {
                return (
                  <DndContext sensors={[sensor]} onDragEnd={(event) => onDragEnd(event, props.id, 2)}>
                    <SortableContext items={form2.getFieldValue(props.id) ? form2.getFieldValue(props.id).map((i: any) => i.uid) : []} strategy={verticalListSortingStrategy}>
                      <ProFormUploadButton
                        {...props}
                        {...props?.fieldProps}
                        icon={<PlusCircleOutlined style={{ fontSize: 30 }} />}
                        title={<div style={{ marginTop: 10, fontSize: 12 }}>点击上传图片</div>}
                        fieldProps={{
                          name: 'file',
                          accept: 'image/*',
                          multiple: true,
                          listType: 'picture-card',
                          headers: {
                            authorization: localStorage.getItem('token') ?? '',
                          },
                          itemRender: (originNode, file) => <DraggableUploadListItem originNode={originNode} file={file} />,
                          beforeUpload(file: RcFile) {
                            const isLt2M = file.size / 1024 / 1024 < 10;
                            if (!isLt2M) {
                              message.error('图片大小不能超过10MB!');
                            }
                            return isLt2M;
                          },
                          onPreview: async (file) => {
                            if (file.response && file.response.retcode) {
                              window.open(file.response.data);
                            } else {
                              window.open(file.url);
                            }
                          },
                        }}
                        action={process.env.BASE_URL + '/oss/imgUpload'}
                        onChange={(a: any) => {
                          props?.fieldProps.onChange(a.fileList);
                        }}
                      />
                    </SortableContext>
                  </DndContext>
                );
              },
            },
          }}
          hashed={false}
        >
          <ProDescriptions
            dataSource={{
              pbcBusinessHead: info.pbcBusinessHead,
              pbcBusinessHeadUserNo: info.pbcBusinessHeadUserNo,
              pbcBusinessStartDate: info.pbcBusinessStartDate,
              pbcBusinessBank: info.pbcBusinessBank,
              pbcBusinessAccountName: info.pbcBusinessAccountName,
              pbcBusinessAccount: info.pbcBusinessAccount,
              pbcBusinessMainCategory: info.pbcBusinessMainCategory,
              pbcBusinessHeadUserNoFrontUrl: info.pbcBusinessHeadUserNoFrontUrl
              ? [
                  {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: info.pbcBusinessHeadUserNoFrontUrl,
                  },
                ]
              : [],
              pbcBusinessHeadUserNoBackUrl: info.pbcBusinessHeadUserNoBackUrl
              ? [
                  {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: info.pbcBusinessHeadUserNoBackUrl,
                  },
                ]
              : [],
              pbcBusinessLicenseUrl: info.pbcBusinessLicenseUrl ? info.pbcBusinessLicenseUrl.split(',').map((e, index) => {
                return {
                  uid: '-' + (index+1),
                  name: 'image.png',
                  status: 'done',
                  url: e,
                }
              }) : [],
            }}
            editable={
              access.businessSave && isEdit
                ? {
                    form: form2,
                    onSave: async (key, record: any, originRow) => {
                      let pbcBusinessHeadUserNoFrontUrl = "";
                      if (
                        key === 'pbcBusinessHeadUserNoFrontUrl' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        if (record[key][0].uid === '-1') {
                          pbcBusinessHeadUserNoFrontUrl = record[key][0].url;
                        }
                        if (record[key][0].response && record[key][0].response.retcode) {
                          pbcBusinessHeadUserNoFrontUrl = record[key][0].response.data;
                        }
                      }
                      let pbcBusinessHeadUserNoBackUrl = "";
                      if (
                        key === 'pbcBusinessHeadUserNoBackUrl' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        if (record[key][0].uid === '-1') {
                          pbcBusinessHeadUserNoBackUrl = record[key][0].url;
                        }
                        if (record[key][0].response && record[key][0].response.retcode) {
                          pbcBusinessHeadUserNoBackUrl = record[key][0].response.data;
                        }
                      }
                      let pbcBusinessLicenseUrl = [];
                      if (
                        key === 'pbcBusinessLicenseUrl' &&
                        record[key] &&
                        record[key].length > 0
                      ) {
                        for (let i = 0; i < record[key].length; i++) {
                          const element = record[key][i];
                          if (element.response && element.response.retcode) {
                            pbcBusinessLicenseUrl.push(element.response.data)
                          } else {
                            pbcBusinessLicenseUrl.push(element.url)
                          }
                        }
                      }
                      await adminChangeBusinessInfoUsingPost({
                        ...info,
                        //@ts-ignore
                        [key]: record[key],
                        pbcBusinessHeadUserNoFrontUrl:
                          key === 'pbcBusinessHeadUserNoFrontUrl' ? pbcBusinessHeadUserNoFrontUrl : info.pbcBusinessHeadUserNoFrontUrl,
                        pbcBusinessHeadUserNoBackUrl:
                          key === 'pbcBusinessHeadUserNoBackUrl' ? pbcBusinessHeadUserNoBackUrl : info.pbcBusinessHeadUserNoBackUrl,
                        pbcBusinessLicenseUrl: key === 'pbcBusinessLicenseUrl' ? pbcBusinessLicenseUrl.join(',') : info.pbcBusinessLicenseUrl
                      })
                        .then((res) => {
                          if (res.retcode) {
                            getInfo();
                            message.success('修改成功');
                            return record;
                          } else {
                            message.error('修改失败');
                            return originRow;
                          }
                        })
                        .catch(() => {
                          return originRow;
                        });
                    },
                  }
                : undefined
            }
            columns={[
              {
                title: '法人',
                key: 'pbcBusinessHead',
                dataIndex: 'pbcBusinessHead',
              },
              {
                title: '法人身份证号',
                key: 'pbcBusinessHeadUserNo',
                dataIndex: 'pbcBusinessHeadUserNo',
              },
              {
                title: '公司成立时间',
                key: 'pbcBusinessStartDate',
                valueType: 'date',
                dataIndex: 'pbcBusinessStartDate',
              },
              {
                title: '开户行',
                key: 'pbcBusinessBank',
                dataIndex: 'pbcBusinessBank',
              },
              {
                title: '商户账户名称',
                key: 'pbcBusinessAccountName',
                dataIndex: 'pbcBusinessAccountName',
              },
              {
                title: '收款账号',
                key: 'pbcBusinessAccount',
                dataIndex: 'pbcBusinessAccount',
              },
              {
                title: '身份证人像面',
                key: 'pbcBusinessHeadUserNoBackUrl',
                dataIndex: 'pbcBusinessHeadUserNoBackUrl',
                span: 1,
                fieldProps: {
                  max: 1
                },
                valueType: 'upload',
              },
              {
                title: '身份证国徽面',
                key: 'pbcBusinessHeadUserNoFrontUrl',
                dataIndex: 'pbcBusinessHeadUserNoFrontUrl',
                span: 2,
                fieldProps: {
                  max: 1
                },
                valueType: 'upload',
              },
              {
                title: '经营范围',
                key: 'pbcBusinessMainCategory',
                valueType: 'textarea',
                span: 3,
                dataIndex: 'pbcBusinessMainCategory',
              },
              
              {
                title: '营业执照',
                key: 'pbcBusinessLicenseUrl',
                dataIndex: 'pbcBusinessLicenseUrl',
                span: 3,
                valueType: 'upload',
              },
            ]}
            bordered
            title="工商信息"
          ></ProDescriptions>
        </ProConfigProvider>
      </ProCard>
    </PageContainer>
  );
};

export default Detail;
