import React from 'react';
import moment from 'moment';
import { PlusOutlined } from '@ant-design/icons';
import { notification, Tag, Tooltip, Input } from 'antd';
import {
  uploadFile,
  apiCategoryList,
  apiAddrArea,
  apiServiceFacility,
  apiBusinessDetail,
  apiBankList,
} from '../service';

export const wrapperCol = {
  xs: { span: 24 },
  sm: { span: 12 },
};
export const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

export const businessTypeDesc = {
  1: '到家业务',
  2: '实物业务',
  3: '到店业务',
};

// 业务模式
export const businessModel = [
  { label: '到家外卖业务(外卖配送业务)', value: 1 },
  { label: '实物商品业务员', value: 2 },
  { label: '到店业务(服务类业务)', value: 3 },
];

export const signDateTypeList = [{ label: '自商品售卖起默认一年', value: 1 }];

export const legalPersonList = [{ label: '长期', value: '长期' }];

// 获取申请信息
export async function getInfo() {
  const data = await apiBusinessDetail();
  let settlementType = 1;
  const res = data.data;
  console.log('res :>> ', res);
  if (!res) {
    return;
  }
  if (res.facilities) {
    res.customList = res.facilities.customList || [];
    res.selfList = res.facilities.selfList || [];
  }
  res.signDateType = res.signDateType ? [res.signDateType] : [];
  res.accountOpenPermitImage = res.accountOpenPermitImage
    ? [{ uid: 0, url: res.accountOpenPermitImage }]
    : [];
  res.businessLicenseImage = res.businessLicenseImage
    ? [{ uid: 0, url: res.businessLicenseImage }]
    : [];
  res.idCardEmblemImage = res.idCardEmblemImage ? [{ uid: 0, url: res.idCardEmblemImage }] : [];
  res.idCardPortraitImage = res.idCardPortraitImage
    ? [{ uid: 0, url: res.idCardPortraitImage }]
    : [];
  res.primaryImage = res.primaryImage ? [{ uid: 0, url: res.primaryImage }] : [];
  res.sealImage = res.sealImage ? [{ uid: 0, url: res.sealImage }] : [];
  res.brandCertificate = res.brandCertificate ? [{ uid: 0, url: res.brandCertificate }] : [];
  // 非同名结算授权文件
  res.differentNameAuthorizationImage = res.differentNameAuthorizationImage
    ? [{ uid: 0, url: res.brandCertificate }]
    : [];
  // 户口本本人页
  res.householdRegisterImage = res.householdRegisterImage
    ? [{ uid: 0, url: res.householdRegisterImage }]
    : [];
  // 工商局
  res.icbProofImage = res.icbProofImage ? [{ uid: 0, url: res.icbProofImage }] : [];
  if (res.categoryQualificateImage && res.categoryQualificateImage.length) {
    res.categoryQualificateImage = res.categoryQualificateImage.map((item, index) => ({
      uid: index,
      url: item,
    }));
  }
  if (res.otherImage && res.otherImage.length) {
    res.otherImage = res.otherImage.map((item, index) => ({
      uid: index,
      url: item,
    }));
  }
  res.addr = [res.provinceId, res.cityId, res.countyId];
  if (res.townId) {
    res.addr.push(res.townId);
  }
  if (settlementType !== null) {
    settlementType = +res.settlementType;
  }
  // 身份证有效期处理
  let checkboxDisabled = false;
  if (res.legalPersonPeriod) {
    const date = res.legalPersonPeriod.split('-') || [];
    res.legalPersonStart = date[0] && moment(date[0]);
    res.legalPersonEnd = date[1] && date[1] !== '长期' ? moment(date[1]) : '';
    res.checked = date[1] && date[1] === '长期' ? ['长期'] : [];
    checkboxDisabled = date[1] && date[1] === '长期';
  }

  // 营业执照
  const businessDate =
    res.businessLicensePeriod.indexOf('-') !== -1 ? res.businessLicensePeriod?.split('-') : [];
  res.businessLicensePeriodBegin = businessDate[0] ? moment(businessDate[0]) : '';
  res.businessLicensePeriodEnd = businessDate[1] ? moment(businessDate[1]) : '';

  const companyNamedis = !!res.companyName;
  // 获取主营类目
  let categoryList = [];
  if (res.productBusiness?.length) {
    const dataList = await apiCategoryList(res.productBusiness);
    categoryList = dataList.data;
  }
  this.setState({
    settlementType,
    businessInfo: res,
    checkboxDisabled,
    companyNamedis,
    categoryList,
    mainCategoryId: res.mainCategoryId,
    companyType: res.companyType,
  });
}

// 删除图片
function delImg(keyName, e) {
  this.setState(state => {
    if (keyName === 'categoryQualificateImage') {
      state.businessInfo.categoryQualificateImage.forEach((item, index) => {
        if (item.uid === e.uid) {
          state.businessInfo.categoryQualificateImage.splice(index, 1);
        }
      });
    } else {
      state.businessInfo[keyName].splice(e.uid, 1);
    }
    return {
      businessInfo: state.businessInfo,
    };
  });
}

// 上传图片
export function uploadPropsFn(
  { keyName, limit = 1, maxSize = 1024 * 1024 * 5, maxSizeMsg = '文件大小不能超过5M！', type = 0 },
  successCallback = () => {},
) {
  const that = this;
  let timer = null;

  return {
    maxSize,
    async customRequest(info) {
      const { file } = info;
      if (info.file.size > maxSize) {
        notification.error({ message: maxSizeMsg });
        return;
      }
      if (that.state.businessInfo[keyName] && that.state.businessInfo[keyName].length >= limit) {
        notification.error({ message: `最多只能上传${limit}个文件！` });
        return;
      }
      const res = await uploadFile([file], type);
      if (res.businessCode !== '0000') {
        return;
      }
      const url = res.data?.[0];
      that.setState(state => {
        const imgList = state.businessInfo[keyName] || [];
        const attachment = {
          uid: imgList.length || 0,
          name: file?.name,
          status: 'done',
          url,
        };
        imgList.push(attachment);
        if (imgList.length <= limit) {
          state.businessInfo[keyName] = imgList;
        } else {
          notification.error({ message: `最多只能上传${limit}个文件！` });
        }
        return {
          businessInfo: state.businessInfo,
        };
      });
      successCallback(keyName, url);
      // 需要把上传的数据存储下来
    },
    disabled: this.state.disabled,
    multiple: limit > 1,
    listType: 'picture-card',
    showUploadList: true,
    accept: '.png,.bmp,.gif,.jpeg,.jpg',
    onRemove: e => delImg.call(this, keyName, e),
    beforeUpload: (e, flist) => {
      const imgList = that.state.businessInfo[keyName] || [];
      if (flist.length + imgList.length > limit) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          notification.error({ message: `最多只能上传${limit}个文件！` });
        }, 100);
        return false;
      }
      return true;
    },
  };
}

/** **** 自定义服务设施 start ***************************** */
// 关闭标签输入框
function handleClose(removedTag) {
  this.setState(state => {
    state.businessInfo.customList = state.businessInfo.customList.filter(tag => tag !== removedTag);
    return {
      businessInfo: state.businessInfo,
    };
  });
}

// 显示标签输入框
function showInput() {
  this.setState({ tagVisible: true }, () => this.input.focus());
}

// 标签内容改变
function handleInputChange(e) {
  if (e && e.target) {
    this.setState({ tagValue: e.target.value });
  }
}

// 保存标签
function handleInputConfirm() {
  const { tagValue } = this.state;
  if (tagValue) {
    let { customList } = this.state.businessInfo;
    if (tagValue && customList.indexOf(tagValue) === -1) {
      customList = [...customList, tagValue];
    }
    this.setState(state => {
      state.businessInfo.customList = customList;
      return {
        businessInfo: state.businessInfo,
        tagVisible: false,
        tagValue: '',
      };
    });
  }
}

// 渲染标签
export function renderServiceTags() {
  const that = this;
  return (
    <div>
      {that.state.businessInfo.customList &&
        that.state.businessInfo.customList.map(tag => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            //  二期放开
            <Tag key={tag} closable onClose={() => handleClose.call(that, tag)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? (
            <Tooltip title={tag} key={tag}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
      {that.state.tagVisible && (
        <Input
          // eslint-disable-next-line react/no-this-in-sfc
          ref={this.saveInputRef}
          type="text"
          size="small"
          style={{ width: 78 }}
          value={that.state.tagValue}
          onChange={e => handleInputChange.call(that, e)}
          onBlur={e => handleInputConfirm.call(that, e)}
          onPressEnter={e => handleInputConfirm.call(that, e)}
        />
      )}
      {/* 二期放开 */}
      {!that.state.tagVisible && (
        <Tag
          onClick={() => showInput.call(that)}
          style={{ background: '#fff', borderStyle: 'dashed' }}
        >
          <PlusOutlined /> 新增
        </Tag>
      )}
    </div>
  );
}
/** **** 自定义服务设施 end ***************************** */

// 获取服务设施
export async function getServiceFacility() {
  const res = await apiServiceFacility();
  if (res.data) {
    this.setState({
      serviceFacilitys: res.data,
    });
  }
}

// 开户行
export async function getBankList() {
  const res = await apiBankList();
  if (res.data) {
    this.setState({
      bankList: res.data,
    });
  }
}

// 获取地址省
export async function getAreaAddr() {
  const data = await apiAddrArea();
  const areaAddr = data.data || null;
  if (areaAddr) {
    const res = areaAddr.map(item => ({
      isLeaf: false,
      loading: false,
      label: item.addrName,
      value: item.addrId,
    }));
    // 编辑时 回显 市、区、街道
    if (this.state.businessInfo.provinceId) {
      const pros = res.filter(item => +item.value === +this.state.businessInfo.provinceId);
      await loadData.call(this, pros);
      const citys = pros[0].children.filter(
        item => +item.value === +this.state.businessInfo.cityId,
      );
      await loadData.call(this, citys);
      if (this.state.businessInfo.townId) {
        const countys = citys[0].children.filter(
          item => +item.value === +this.state.businessInfo.countyId,
        );
        await loadData.call(this, countys);
      }
    }
    this.setState({
      areaAddr: res,
    });
  }
}

// 获取市区街道
export async function loadData(selectedOptions) {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  const data = await apiAddrArea({
    parentId: targetOption.value,
  });
  const areaAddr = data.data || null;
  if (areaAddr) {
    const children = areaAddr.map(item => ({
      isLeaf: +item.addrLevel === 4,
      loading: false,
      label: item.addrName,
      value: item.addrId,
    }));
    targetOption.loading = false;
    if (children.length > 0) {
      targetOption.children = children;
    } else {
      targetOption.isLeaf = true;
    }
    this.setState({
      // eslint-disable-next-line react/no-access-state-in-setstate
      areaAddr: [...this.state.areaAddr],
    });
  }
}
